使用read.csv,我从 .csv 文件中读取了一个数据框,其中的数据排列如下:
team1 team2 team3
Andy Alice Karen
Bob Belle Kyle
Chad Carol
Diana
Run Code Online (Sandbox Code Playgroud)
team <- read.csv("team.csv")
Run Code Online (Sandbox Code Playgroud)
数据框属于因子类,尺寸为 4x3。对于team1和team3列,额外的空行用 来显示""。我想使用转换将列提取为向量as.character。但是如何缩短这个向量并排除""元素呢?例如:
team1_list <- as.character(team$team1)包括尾随""元素。我只想得到向量("Andy", "Bob", "Chad")而不是("Andy", "Bob", "Chad", "")
akr*_*run 10
nzchar使用起来更方便base R
str1[nzchar(str1)]
#[1] "Andy" "Bob" "Chad"
Run Code Online (Sandbox Code Playgroud)
str1 <- c("Andy", "Bob", "Chad", "")
Run Code Online (Sandbox Code Playgroud)
小智 6
另一种选择是使用stri_remove_empty包stringi来删除向量的空字符串。
library(stringi)
str <- c("Andy", "Bob", "Chad", "")
team1_list <- as.character(stri_remove_empty(str, na_empty = FALSE))
team1_list
#[1] "Andy" "Bob" "Chad"
Run Code Online (Sandbox Code Playgroud)
由于不存在数据,您可以尝试以下选项之一:
选项1:
#Code1
team1_list <- as.character(team$team1[team$team1!=""])
Run Code Online (Sandbox Code Playgroud)
选项2:
#Code2
team1_list <- as.character(team$team1[levels(team$team1)!=""])
Run Code Online (Sandbox Code Playgroud)