我的数据框中有一列由逗号分隔的数字字符串组成。我想将字符串转换为数字列表,然后得到均值。我的数据框df
:
a3
1,5,2
103.1
34,6
首先,我将字符串转换为列表:
> df$a3_list <- strsplit(as.character(df$a3), split = ',')
新df
:
a3 a3_list
1,5,2 c("1", "5", "2")
103.1 103.1
34,6 c("34", "6")
但是,此时,我不确定如何在df$a3_list
答案 0 :(得分:3)
您可以使用stringi
,快速
library(stringi)
mat <- stri_split_fixed(df$a3, ',', simplify=T)
mat <- `dim<-`(as.numeric(mat), dim(mat)) # convert to numeric and save dims
rowMeans(mat, na.rm=T)
# [1] 2.666667 103.100000 20.000000
或与Base R
sapply(strsplit(as.character(df$a3), ",", fixed=T), function(x) mean(as.numeric(x)))
答案 1 :(得分:2)
另一个base R
选项
rowMeans(read.table(text=df$a3, sep=",", fill=TRUE), na.rm=TRUE)
#[1] 2.666667 103.100000 20.000000
注意:假设&#39; a3&#39;是character
类。否则,请使用as.character(df$a3)
df <- structure(list(a3 = c("1,5,2", "103.1", "34,6")), .Names = "a3",
class = "data.frame", row.names = c(NA, -3L))