在字符串向量中删除空字符""的元素

11
使用read.csv函数,我从CSV文件中读取了一个数据框,其中的数据是按照以下方式排列的:
team1 team2 team3
Andy  Alice  Karen
Bob   Belle  Kyle
Chad  Carol  
      Diana

team <- read.csv("team.csv")

数据框是因子类,维度为4x3。对于team1team3列,额外的空行用""表示。 我想使用as.character转换提取列作为向量。但是如何缩短这个向量并排除""元素?例如: team1_list <- as.character(team$team1) 包括尾部的""元素。我只想要("Andy", "Bob", "Chad")而不是("Andy", "Bob", "Chad", "")的向量。

1
尝试使用以下代码:team1_list <- as.character(team$team1[team$team1!=""]) 或者 team1_list <- as.character(team$team1[levels(team$team1)!=""]) - Duck
3个回答

8

使用base R中的nzchar更容易

str1[nzchar(str1)]
#[1] "Andy" "Bob"  "Chad"

数据

str1 <- c("Andy", "Bob", "Chad", "")

5

使用 stringi 包中的 stri_remove_empty 函数,可以删除向量中的空字符串。

library(stringi)
str <- c("Andy", "Bob", "Chad", "")
team1_list <- as.character(stri_remove_empty(str, na_empty = FALSE))
team1_list
#[1] "Andy" "Bob"  "Chad"

2
这个函数非常有用。 - jaeyeon

3

由于没有数据,您可以尝试以下选项之一:

选项1:

#Code1
team1_list <- as.character(team$team1[team$team1!=""])

选项2:

#Code2
team1_list <- as.character(team$team1[levels(team$team1)!=""])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接