2015-11-30 52 views
0

在数据帧创建新的列我有一个DF,如下所示:错误中的R

 id type start end features 
1  5 word  1 2  NN 
2  6 word  3 3  . 
3  7 word  5 12  NN 
4  8 word 14 19  VBZ 
5  9 word 21 30  NN 
6 10 word 32 32  WDT 
7 11 word 34 37  VBP 
8 12 word 39 41  IN 
9 13 word 43 44  IN 
10 14 word 46 46  DT 

我想创建一个新的列“总和”与“开始”和“结束”的每个值的总和。

我创建了以下功能:

mySum <- function(row) { 
     row["start"]+row["end"] 
    } 
    df$sum <- apply(df,1, mySum); 

但是当我运行此我得到以下错误:

Error in row["start"] + row["end"] : 
    non-numeric argument to binary operator 

但如果我只保留行[“开始”]或行[”结束“],它会被创建。

我也试图强制列中的每个值都是数字。

df$start = as.integer(as.vector(df$start)); 
df$end = as.integer(as.vector(df$end)); 

但我仍然得到相同的错误,只有当我添加的值。

我的数据帧的结构如下: 后,我跑了dput(droplevels(head(df,10)))

structure(list(id = 5:14, type = c("word", "word", "word", "word", 
"word", "word", "word", "word", "word", "word"), start = c(1L, 
3L, 5L, 14L, 21L, 32L, 34L, 39L, 43L, 46L), end = c(2L, 3L, 12L, 
19L, 30L, 32L, 37L, 41L, 44L, 46L), features = list(structure(list(
    POS = "NN"), .Names = "POS"), structure(list(POS = "."), .Names = "POS"), 
    structure(list(POS = "NN"), .Names = "POS"), structure(list(
     POS = "VBZ"), .Names = "POS"), structure(list(POS = "NN"), .Names = "POS"), 
    structure(list(POS = "WDT"), .Names = "POS"), structure(list(
     POS = "VBP"), .Names = "POS"), structure(list(POS = "IN"), .Names = "POS"), 
    structure(list(POS = "IN"), .Names = "POS"), structure(list(
     POS = "DT"), .Names = "POS"))), .Names = c("id", "type", 
"start", "end", "features"), row.names = c(NA, 10L), class = "data.frame") 
+0

需要注意的是,所采取的所有铸造的问题分开,如果你用你的错误很可能会发生变化: 'mySum < - 功能(行){ as.integer(行[ “开始”])+ as.integer (行[[“end”]]) }' 根据定义,'row'不能是你认为它的向量。 – Vongo

回答

1

只是做

df1$Sum <- df1[,'start']+ df1[,'end'] 
df1$Sum 
#[1] 3 6 17 33 51 64 71 80 87 92 

或者

rowSums(df1[c('start', 'end')], na.rm=TRUE) 
#1 2 3 4 5 6 7 8 9 10 
#3 6 17 33 51 64 71 80 87 92 

error建议您有非数字列。检查str(df1)。如果班级是factorcharacter,那么将其更改为numeric,并应用上述代码。例如,如果列factor,我们转换为numeric

df1[c('start', 'end')] <- lapply(df1[c('start', 'end')], 
       function(x) as.numeric(as.character(x))) 

character列的情况下,只需使用as.numeric

+0

所以'功能'列是一个列表,'类型'列是一个字符。但我不明白的是,我既没有使用,我只使用'开始'和'结束'(这是数字)。我还应该更新其他列吗? – Mahesh

+0

@Mahesh因为你没有使用'feature'列和'type'列,所以它并不重要。 'start'和'end'列的'class'是什么? – akrun

+0

我运行类(df $ start)和类(df $ end),并给出了“整数” – Mahesh