14

Using read.csv, I have a dataframe read from .csv file which has data arranged as following:

team1 team2 team3
Andy  Alice  Karen
Bob   Belle  Kyle
Chad  Carol  
      Diana
team <- read.csv("team.csv")

The data frame is of factor class and have dimension or 4x3. For team1 and team3 columns, the extra empty rows are show with "". I want to extract the column as a vector using as.character conversion. But how do I shorten this vector exclude the "" elements? For eg.:

team1_list <- as.character(team$team1) includes the trailing "" element. I just want to have the vector of ("Andy", "Bob", "Chad") and not ("Andy", "Bob", "Chad", "")

1
  • 1
    Try this team1_list <- as.character(team$team1[team$team1!=""]) or team1_list <- as.character(team$team1[levels(team$team1)!=""]) Commented Sep 11, 2020 at 17:49

3 Answers 3

11

It is easier to use nzchar from base R

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

data

str1 <- c("Andy", "Bob", "Chad", "")
Sign up to request clarification or add additional context in comments.

Comments

9

Another option using stri_remove_empty of stringi package to remove empty string of vector.

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

1 Comment

This function is super useful.
4

As no data is present you can try one of these options:

Option 1:

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

Option 2:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.