我如何计算r中字符变量的总和
How can i calculate sum of character variable in r
输入
我的数据
a <- c('1','2','3','1','1')
b <- c('3','1','2','1','2')
j <- data.frame(a,b)
rowSums(j) #error
如何计算行的总和?
如果你有 real character
向量(不像你的例子中的 factor
s)你可以使用 data.matrix
为了将所有列转换为 numeric
class
j <- data.frame(a, b, stringsAsFactors = FALSE)
rowSums(data.matrix(j))
## [1] 4 3 5 2 3
否则,您必须先转换为 character
,然后再转换为 numeric
,以免丢失信息
rowSums(sapply(j, function(x) as.numeric(as.character(x))))
## [1] 4 3 5 2 3
输入
我的数据
a <- c('1','2','3','1','1')
b <- c('3','1','2','1','2')
j <- data.frame(a,b)
rowSums(j) #error
如何计算行的总和?
如果你有 real character
向量(不像你的例子中的 factor
s)你可以使用 data.matrix
为了将所有列转换为 numeric
class
j <- data.frame(a, b, stringsAsFactors = FALSE)
rowSums(data.matrix(j))
## [1] 4 3 5 2 3
否则,您必须先转换为 character
,然后再转换为 numeric
,以免丢失信息
rowSums(sapply(j, function(x) as.numeric(as.character(x))))
## [1] 4 3 5 2 3