R 如何转换table()命令以从第三列接收频率?
有这样一个数据帧:R 如何转换table()命令以从第三列接收频率?,r,R,有这样一个数据帧: df1 <- data.frame(stock = c("Google, Yahoo", "Google", "Yahoo, Google", "Amazon, Google", "Google, Amazon"), investor = c("Nathalie","George","Nathalie, George", "Melanie, George","Melanie")) 如何可能添加一个过滤器,以获得每只股票的频率,但基于显示投资者选择偏好的第三列。 以下是
df1 <- data.frame(stock = c("Google, Yahoo", "Google", "Yahoo, Google", "Amazon, Google", "Google, Amazon"), investor = c("Nathalie","George","Nathalie, George", "Melanie, George","Melanie"))
如何可能添加一个过滤器,以获得每只股票的频率,但基于显示投资者选择偏好的第三列。
以下是预期输出的示例:
data.frame(investor = c("Nathalie", "George", "George", "George", "Melanie", "Malanie"), stock = c("Google, Yahoo", "Google", "Google, Yahoo", "Amazon, Google", "Amazon, Google", "Amazon"), frq = c(2,1,1,1,1,1))
再添加一列:
df1 <- data.frame(stock = c("Google, Yahoo", "Google", "Yahoo, Google", "Amazon, Google", "Google, Amazon"), investor = c("Nathalie","George","Nathalie, George", "Melanie, George","Melanie"), year = c("2017", "2018", "2017", "2018", "2017"))
df1在我们像上一步一样对值进行排序后,不要直接执行表
,而是通过赋值来更新列,然后我们可以使用tidyverse
方法拆分“investor”行,并使用add\u count
library(tidyverse)
df1$stock <- sapply(strsplit(as.character(df1$stock), ", "),
function(x) toString(sort(x)))
df1 %>%
mutate_if(is.factor, as.character) %>%
separate_rows(investor) %>%
add_count(stock, investor, year)
库(tidyverse)
df1美元股票%
如果(is.factor,as.character)%>%,则进行变异
单独行(投资者)%>%
添加计数(股票、投资者、年份)
是否拆分“投资者”的名称@akrun是的,我想为此拆分投资者的名称case@akrun或者可能是像meltI这样的东西,我没有得到您显示的准确输出df1$stock%mutate\u all(as.character)%%>%separate\u rows(investor)%%>%add\u count(stock,investor)
@akrun谢谢。你又对了!
df1 <- data.frame(stock = c("Google, Yahoo", "Google", "Yahoo, Google", "Amazon, Google", "Google, Amazon"), investor = c("Nathalie","George","Nathalie, George", "Melanie, George","Melanie"), year = c("2017", "2018", "2017", "2018", "2017"))
library(tidyverse)
df1$stock <- sapply(strsplit(as.character(df1$stock), ", "),
function(x) toString(sort(x)))
df1 %>%
mutate_if(is.factor, as.character) %>%
separate_rows(investor) %>%
add_count(stock, investor, year)