簡體   English   中英

給定數據框中變量的頻率,如何更改數據框行中變量的名稱?

[英]How can I change the name of a variable in a data frame's row given that variable's frequency in the data frame?

我在電影的 data.frame 中有一個變量(分發器,格式 = 因子)。 我想將出現次數少於 10 次的所有經銷商的名稱替換為“小公司”。 我能夠想出一個列表並使用

aggregate(data.frame(count = distributor), list(value = distributor), length)

但我無法在我的 data.frame 中替換。

這是使用dplyr的解決方案。

library(dplyr)

## make some dummy data
df <- tribble(
     ~distributor, ~something,
     "dist1", 89,
     "dist2", 92,
     "dist3", 29,
     "dist1", 89
)


df %>% 
     group_by(distributor) %>% 
     ## this counts the number of occurences of each distributor
     mutate(occurrences = n()) %>% 
     ungroup() %>% 
     ## change the name of the distributor if the occurrences are less than 2
     mutate(distributor = ifelse(occurrences < 2, "small company", distributor))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM