[英]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.