Home > Enterprise >  put the name of the people who have some value in some column
put the name of the people who have some value in some column

Time:08-16

I want to put the name of the people who have some value in some column.

mi df is:

name<-c("luis", "John", "Leo")
a1<-c("a","b",NA)
a2<-c("c",NA,"d")
a3<-c(NA,"d","e")

df<-data.frame(name,a1,a2,a3)

I want to get a result like this

a1: "Luis", "John"
a2: "Luis", "Leon"
a3: "John", "Leo" 

CodePudding user response:

You can try aggregate stack like below

> df[-1] <- ifelse(!is.na(unlist(df[-1])), df$name, NA)

> aggregate(. ~ ind, stack(df[-1]), toString)
  ind     values
1  a1 luis, John
2  a2  luis, Leo
3  a3  John, Leo

CodePudding user response:

You can use lapply to subset df$name in cases where the value not is.na.

lapply(df[-1], function(x) df$name[!is.na(x)])
#$a1
#[1] "luis" "John"
#
#$a2
#[1] "luis" "Leo" 
#
#$a3
#[1] "John" "Leo" 

Or in a different format using toString and stack.

rev(stack(lapply(df[-1], function(x) toString(df$name[!is.na(x)]))))
#  ind     values
#1  a1 luis, John
#2  a2  luis, Leo
#3  a3  John, Leo

or

sapply(df[-1], function(x) toString(df$name[!is.na(x)]))
#          a1           a2           a3 
#"luis, John"  "luis, Leo"  "John, Leo" 
  • Related