Home > Software engineering >  Retrun a new dataframe or list under a condition
Retrun a new dataframe or list under a condition

Time:03-04

I have a dataframe with codes (as number) and characters. If the combinations exist the return value is 1 otherwise the return value is 0.

code A B C D
1    0 1 1 0
2    1 0 0 0
3    0 0 0 1
4    1 1 1 1 

I want to create the output where for every code the characters are shown which are 1 (condition is that the match between code and charcter is 1).
output in a list or dataframe

1: B C
2: A
3: D
4: A B C D

CodePudding user response:

If you want the letters as vectors in a list you can do:

apply(df[2:5], 1, function(x) names(df[2:5])[x == 1])
#> [[1]]
#> [1] "B" "C"
#>
#> [[2]]
#> [1] "A"
#>
#> [[3]]
#> [1] "D"
#>
#> [[4]]
#> [1] "A" "B" "C" "D"

If you want them as a single vector of concatenated strings you can do:

apply(df[2:5], 1, function(x) paste(names(df[2:5])[x == 1], collapse = " "))
#> [1] "B C"     "A"       "D"       "A B C D"

If you want them as a column in your data frame, you can do:

df$result <- apply(df[2:5], 1, function(x) paste(names(df[2:5])[x == 1], collapse = " "))

df
#>   code A B C D  result
#> 1    1 0 1 1 0     B C
#> 2    2 1 0 0 0       A
#> 3    3 0 0 0 1       D
#> 4    4 1 1 1 1 A B C D
  •  Tags:  
  • r
  • Related