Reputation: 937
I am relatively new to R. I have a dataframe that has a column stored as a list. My column contain c("Benzo", "Ferri")
or character(0)
if it's empty. How can I change them to simply Benzo, Ferri
and an empty string for character(0) instead?
I'm not able to, for instance df$general_RN <- unlist(df$general_RN)
because Error in $<-.data.frame(*tmp*, general_RN, value = c("Drug Combinations", : replacement has 1992 rows, data has 10479
I am assuming that all the character(0)
have been removed but I need them retained as NA
s.
Here is what the column looks like
general_RN
c("Chlorambucil", "Vincristine", "Cyclophosphamide")
Pentazocine
character(0)
character(0)
c("Ampicillin", "Trimethoprim")
character(0)
I have ashamedly spent an hour on this problem.
Thanks for your advice.
Upvotes: 4
Views: 3026
Reputation: 7023
It's tough to say without more information about your data, but maybe this can be a solution for you, or at least point you into the right direction:
a <- list('A',character(0),'B')
> a
[[1]]
[1] "A"
[[2]]
character(0)
[[3]]
[1] "B"
> unlist(lapply(a,function(x) if(identical(x,character(0))) ' ' else x))
[1] "A" " " "B"
So in your case that should be:
df$general_RN <- unlist(lapply(df$general_RN,function(x) if(identical(x,character(0))) ' ' else x))
HTH
Upvotes: 7