简体   繁体   English

将频率分配为 r 中的新列

[英]assign frequency as new column in r

Let's say I have the following string:假设我有以下字符串:

a <- c("a", "b", "c", "b", "a", "a", "e")
b <- table(a)

b gives me the frequency of every element in a. b 给了我 a 中每个元素的频率。 How do I create a dataframe with two columns, the first column is a and in the second I have the frequency of each element?如何创建具有两列的 dataframe,第一列是 a,第二列是每个元素的频率?

The output should look like this: output 应如下所示:

f <- c(3, 2, 1, 2, 3, 3, 1)
output <- data.frame(a,f)

Thank you very much in advance!非常感谢您!

We can use add_count to create a new column我们可以使用add_count创建一个新列

library(tibble)
library(dplyr)
tibble(a) %>% 
     add_count(a)

Or in base R with ave或者在带有avebase R

data.frame(a, freq = ave(seq_along(a), a, FUN = length))

Or if it needs to be from 'b', do the match with the names of 'b' and the vector 'a' to expand the table output and then convert the table object to data.frame with as.data.frame或者如果它需要来自'b',则与'b'的名称和向量'a'匹配以扩展table output,然后将table object转换为带有as.data.frame的data.frame

as.data.frame(b[a])
#  a Freq
#1 a    3
#2 b    2
#3 c    1
#4 b    2
#5 a    3
#6 a    3
#7 e    1

Using merge:使用合并:

merge(as.data.frame(a), as.data.frame(table(a)))

#  a Freq
#1 a    3
#2 a    3
#3 a    3
#4 b    2
#5 b    2
#6 c    1
#7 e    1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM