簡體   English   中英

在 R 數據框中輸入缺失值

[英]imputing missing values in R dataframe

我正在嘗試通過匹配另一個數據集中的值來估算我的數據集中的缺失值。

這是我的數據:

df1 %>% head()
           
   <V1>       <V2>     
1  apple       NA 
2  cheese      NA        
3  butter      NA               
 
df2 %>% head()
           
   <V1>      <V2>     
1  apple     jacks           
2  cheese    whiz      
3  butter    scotch
4  apple     turnover           
5  cheese    sliders      
6  butter    chicken
7  apple     sauce           
8  cheese    doodles      
9  butter    milk

這就是我希望 df1 的樣子:

   <V1>       <V2>     
1  apple      jacks, turnover, sauce
2  cheese     whiz, sliders, doodles        
3  butter     scotch, chicken, milk 

這是我的代碼:

df1$V2[is.na(df1$V2)] <- df2$V2[match(df1$V1,df2$V1)][which(is.na(df1$V2))]

此代碼工作正常,但它只提取第一個缺失值並忽略其余部分。

我認為您甚至不需要導入 df1 在這種情況下可以基於 df2 完成所有操作

df1 <- df2 %>% group_by(`<V1>`) %>% summarise(`<V2>`=paste0(`<V2>`, collapse = ", "))

僅使用基礎 R 的另一種解決方案

aggregate(DF2$V2, list(DF2$V1), c, simplify=F)
  Group.1                      x
1   apple jacks, turnover, sauce
2  butter  scotch, chicken, milk
3  cheese whiz, sliders, doodles

暫無
暫無

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

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