[英]How to compute the NAs with the column mean and then multiply columns of different lengths in R?
[英]How to compute frequency with different lengths of string
我从R开始,有时候对我来说有点难。 我有一个包含100000个观测值的大数据框,并且在此数据框中有一个列ID,我需要计算该列中最频繁的ID。 但是问题在于,有时在字符串中会有不同的ID,并用'&'分隔。 我要举一个例子,这比较容易:
id value
1 1
1 2
2&3&4 6
2&5&7&8 1
2&4&5 3
2 3
因此,我应该获得2
字符串中最多可以包含20个“&”。
提前致谢,
数据似乎是这样的:
df<-structure(list(id = structure(c(1L, 1L, 3L, 5L, 4L, 2L), .Label = c("1",
"2", "2&3&4", "2&4&5", "2&5&7&8"), class = "factor"), value = c(1L,
2L, 6L, 1L, 3L, 3L)), .Names = c("id", "value"), class = "data.frame", row.names = c(NA,
-6L))
第一步是拥有一个包含所有ids
的向量:
unlist(strsplit(as.character(df[,1]),'&'))
# [1] "1" "1" "2" "3" "4" "2" "5" "7" "8" "2" "4" "5" "2"
然后我们得到频率:
table(unlist(strsplit(as.character(df[,1]),'&')))
# 1 2 3 4 5 7 8
# 2 4 1 2 2 1 1
然后我们以最高的频率显示数字(表格以降序排列):
names(sort(table(unlist(strsplit(as.character(df[,1]),'&'))),decreasing=T)[1])
# [1] "2"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.