Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrun a new dataframe or list under a condition

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading