使用R中的列表和列表名称的值替换数据框列的值 [英] replacing values of a dataframe column using values of a list and list name in R

查看:34
本文介绍了使用R中的列表和列表名称的值替换数据框列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用列名替换列中的值,条件是该值位于列表值之内:

I would like to replace Values inside of a column with a list name conditional upon the values being inside the list values:

df <- data.frame(Activity = c("Checking emails", "Playing games", "Reading", "Watching TV", 
                         "Watching YouTube", "Watching TV", "Relaxing", "Getting ready", 
                         "Working/ studying", "Relaxing"))

mylist <-list(Tech_activity = c("Browsing social media", "Checking emails", 
"Video calling", "On my computer/ PC", "Watching YouTube", "Browsing the internet", 
"On my phone", "Watching TV"), Socialising = c("Spending time with friends", 
"Chatting/ talking/ having a conversation", "Spending time with family"
), Work = "Working/ studying", Transport = c("Travelling", "Walking", 
"Driving"), Household = c("Housework", "Cooking"), Leisure = c("Exercising/ Working out", 
"Getting ready", "Exercising/ working out", "Hobbies eg knitting", 
"Playing games", "Shopping", "Eating", "Listening to music", 
"Reading", "Smoking", "Playing with pets", "Personal caring", 
"Personal care", "Nothing", "Relaxing", "Waiting")) 

因此,如果数据帧值位于列表中某个元素的值中,则将df替换为该元素名称,如果不跳过该元素,则检查列表中的下一个元素,依此类推.(请原谅双循环).

So if the data frame value is in the values of an element in the list, then replace the df with that element name, if not skip that element and check the next element of the list and so on. (Please excuse the double for-loop).

for (i in df$Activity){
  for (j in mylist){
    if (i %in% mylist[j]){
      i <- names(mylist[j])
    }
  }
}

谢谢您的帮助.

推荐答案

您可以将 mylist 作为数据框,然后与 df 进行合并

You can make mylist as dataframe and then merge it with df.

merge(df, stack(mylist), by.x = 'Activity', by.y = 'values')


tidyverse 的方式是:

library(tidyverse)

enframe(mylist) %>%
  unnest(value) %>%
  right_join(df, by = c('value' = 'Activity'))

#   name          value            
#   <chr>         <chr>            
# 1 Tech_activity Checking emails  
# 2 Tech_activity Watching YouTube 
# 3 Tech_activity Watching TV      
# 4 Tech_activity Watching TV      
# 5 Work          Working/ studying
# 6 Leisure       Getting ready    
# 7 Leisure       Playing games    
# 8 Leisure       Reading          
# 9 Leisure       Relaxing         
#10 Leisure       Relaxing         

这篇关于使用R中的列表和列表名称的值替换数据框列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆