我有一个如下的嵌套框架。我想添加列count 1和count 2,这样所有的值都在col 1和col 2中计数。因此,第1行的count 1将是4,因为10在两列中出现了4次,Freqcol 1将是4/6
ID col1 col2
1 10 12
2 10 15
3 10 10
字符串
所需输出:
ID col1 col2 count1 count2 Freqcol1 Freqcol2
1 10 12 4 1 0.66 0.16
2 10 15 4 1 0.66 0.16
3 10 10 4 4 0.66 0.66
型
这是我尝试的,似乎给予错误的输出。
count_occurrences <- function(data) {
unique_numbers <- unique(c(data$col1, data$col2))
# Count occurrences for each number in Column1
count1 <- table(data$col1)
data$occurrences_col1 <- count_col1[match(data$col1, unique_numbers)]
# Count occurrences for each number in Column2
count_col2 <- table(data$col2)
data$occurrences_col2 <- count_col2[match(data$col2, unique_numbers)]
return(data) }
# Count occurrences and add to the data frame
result_data <- count_occurrences(mydata)
print(result_data)
型
2条答案
按热度按时间xytpbqjk1#
你可以用R来实现:
字符串
jv2fixgn2#
你可以试试
pivot_*
字符串
这给
型