如何在R Dataframe中通过向量 [英] How can I go through a vector in R Dataframe

查看:163
本文介绍了如何在R Dataframe中通过向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框

I have a dataframe that looks like this

Name   Cricket   Football   Swimming 
A      Y         Y          N
B      N         Y          N
C      Y         N          Y

我想要一个遍历所有列并使用该列标记每个条目的代码像这样的名字:

I want a code that goes through all the columns and flags each entry using the column name like this:

Name   Cricket   Football   Swimming   Sports
A      Y         Y          N          Cricket and Football
B      N         Y          N          Football Only
C      Y         N          Y          Cricket and Swimming

我有一个使用ifelse()的想法,但是如果数据框的列数增加了,我需要动态的东西,而我每次都不需要更改。

I have an idea of using ifelse() but it would be tedious if the dataframe increases in number of columns and i need something dynamic which i do not need to change everytime.

请帮忙!

推荐答案

一种选择是将收集数据转换为'long'格式,过滤器带有 Y的行(按名称分组),将元素粘贴到键中( str_c )和 left_join 与原始数据集

An option would be to gather the data into 'long' format, filter the rows with 'Y', grouped by 'Name', paste the elements in 'key' (str_c) and left_join with the original dataset

library(tidyverse)
df1 %>%
   gather(key, val, -Name) %>% 
   filter(val == 'Y') %>% 
   group_by(Name) %>% 
   summarise(Sports = str_c(key, collapse= ' and ')) %>%
   left_join(df1) %>%
   select(names(df1), "Sports")
# A tibble: 3 x 5
#  Name  Cricket Football Swimming Sports              
#  <chr> <chr>   <chr>    <chr>    <chr>               
#1 A     Y       Y        N        Cricket and Football
#2 B     N       Y        N        Football            
#3 C     Y       N        Y        Cricket and Swimming



数据



data

df1 <- structure(list(Name = c("A", "B", "C"), Cricket = c("Y", "N", 
"Y"), Football = c("Y", "Y", "N"), Swimming = c("N", "N", "Y"
)), class = "data.frame", row.names = c(NA, -3L))

这篇关于如何在R Dataframe中通过向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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