Unlist a column while retaining character(0) as empty strings in R

萝らか妹 提交于 2019-12-10 10:54:11

问题


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 NAs.

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.


回答1:


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



来源:https://stackoverflow.com/questions/44659559/unlist-a-column-while-retaining-character0-as-empty-strings-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!