在R中将字符(0)保留为空字符串的同时取消列出列 [英] Unlist a column while retaining character(0) as empty strings in R

查看:74
本文介绍了在R中将字符(0)保留为空字符串的同时取消列出列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R比较陌生.我有一个数据框,其中有一个列存储为列表.我的列包含c("Benzo", "Ferri")character(0)(如果为空).我如何才能将它们更改为简单的Benzo, Ferri以及一个用于字符(0)的空字符串?

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?

我无法使用,例如df$general_RN <- unlist(df$general_RN),因为Error in $<-.data.frame(*tmp*, general_RN, value = c("Drug Combinations", : replacement has 1992 rows, data has 10479

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

我假设所有character(0)已被删除,但我需要将它们保留为NA s.

I am assuming that all the character(0) have been removed but I need them retained as NAs.

这是该列的样子

general_RN
c("Chlorambucil", "Vincristine", "Cyclophosphamide")
Pentazocine
character(0)
character(0)
c("Ampicillin", "Trimethoprim")
character(0)

我很problem愧地花了一个小时解决这个问题.

I have ashamedly spent an hour on this problem.

感谢您的建议.

推荐答案

如果没有有关数据的更多信息很难说,但这也许可以为您提供解决方案,或者至少可以为您指明正确的方向:

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"

因此您的情况应该是:

df$general_RN <- unlist(lapply(df$general_RN,function(x) if(identical(x,character(0))) ' ' else x))

HTH

这篇关于在R中将字符(0)保留为空字符串的同时取消列出列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆