1

我是 R 的新手,这真的很基础,但它不适合我。我想对这个 data.frame 中 col 6:11 的行求和,例如:

输入(tab.res)

tab.res <-结构(c(“RIL”,“RIL”,“RIL”,“RIL”,“RIL”,“RIL”,“RIL”,“RIL”,“RIL”,“1993”,“ 1994“,”,“ 1995”,“ 1996”,“ 1998”,“ 2000”,“ 2003”,“ 2006”,“ 2006”,“ 2009”,“ 0.622648030237929”,“ 0.622780354568876 , "0.62229896748978", "0.619100952240793", "0.62242230375717", "0.621052639967347", "21.8279151394679", "18.558235100949", "19.1066487340136", "19.4658454721166", "19.7990392265612", "20.5366574203101", "22.3737846431613", "21.6823832708024", "22.5832057096871", "558.462585034014", "460.190476190476", "457.319727891156", "455.210884353742", "437.78231292517", "455.360544217687", "569.442176870748", "488.367346938776", "512.421768707483", "42.048152226551", "35.7094330210724" , "36.4311339004591", "35.8460590917321", "33.3991893243174", "33.9938868563961", "39.9166803633779", "34.7098561898221", "35.4769784708925", "44.0903088045558", "40.5555666070647", "41.419372563604", "43.5776682933757", "45.5922072021568", " 46.0154886164247", "47.3378504648163", "46.41940144389", "49.5580273139249", "40.6511227624141", "39.1466514500133", "40.4409858368967", "41.4903119307394", "42.9108185069093", "45.7459942527593", "47.7880868127877", "48.8291523581031", "48.3273707080036", "31.3644667603767", "31.0971941969479", "32.4804982013221" , "32.4553994494653", "34.2369548403931", "35.6674106248615", "38.53520691726", "38.8160980443", "40.8055122694451", "24.5415097525631", "23.5956393932039", "23.6298291129159", "24.6786066881199", "25.3372707363408", "25.7293935423119", " 26.2842616375337”、“29.2438109789201”、“29.6350482936186”、“76.6236464549925", "44.5672068727091", "46.962777170159", "48.0267179639631", "51.298941016064", "53.5121260383574", "55.4511984380194", "53.5652556461721", "55.2830178740705"), .Dim = c(9L, 11L), .Dimnames = list (NULL,c(“治疗”,“年”,“WD”,“BA”,“StemD”,“AGB.10.20”,“AGB.20.30”,“ABG.30.40”,“ABG.40.50”,“ ABG.50.60"、"ABG.60.+")))Dimnames = list(NULL, c("Treat", "Year", "WD", "BA", "StemD", "AGB.10.20", "AGB.20.30", "ABG.30.40", "ABG.40.50 ", "ABG.50.60", "ABG.60.+")))Dimnames = list(NULL, c("Treat", "Year", "WD", "BA", "StemD", "AGB.10.20", "AGB.20.30", "ABG.30.40", "ABG.40.50 ", "ABG.50.60", "ABG.60.+")))

这应该解决了这个问题:

tab.res$total <- rowSums(subset(tab.res, select=6:11))

但我不断得到:

rowSums(subset(tab.res, select = 6:11)) 中的错误:“x”必须是数字

我尝试使用“as.numeric”来转换出现错误的任何内容,但我没有得到任何结果......有人打电话告诉我问题出在哪里?

4

1 回答 1

2

您应该使用数据框,而不是矩阵,因为您确实有几种不同的数据类型。我怀疑您可以从一开始就将数据作为数据框读取,但是如果您想将您拥有的内容转换tab.res为数据框,并在第 3-11 列中使用数值:

tab.res <- as.data.frame(tab.res, stringsAsFactors=FALSE)
for (column in 3:11) {
  tab.res[, column] <- as.numeric(tab.res[, column])
}

(我知道,通常最好使用名称而不是列号,但正如我所说,这一步可能无论如何都没有必要。)

于 2013-08-16T20:23:21.977 回答