Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing character length of list columns in R

In R, I have a table with headers and each column has a different character lengths. i.e.

#   Level1   Level2   Level3
#1   a       d         e
#2   b       *blank*   f
#3   c       *blank*   *blank*

This is the code I read in to covert my df to a list.

df=read.csv("list.csv", header=TRUE, sep = ",")
lst1=list() 
for(i in 1:ncol(df)) {      
  lst1[[i]] <- df[ , i]    
}
names(lst1)=colnames(df)
print(lst1)
str(lst1)

However, I receive a list with the same character length. i.e.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List of 3
 $ level1: chr [1:3] "a" "b" "c"
 $ level2: chr [1:3] "d" "" ""
 $ level3: chr [1:3] "e" "f" ""

Is there a way to altering the list so the characters reflect the actual list length for each of the 3 object?

Many thanks.

>Solution :

You can try this, it’s going to remove all the ""s in your elements of the list:

result <- lapply(lst1, function(x) x[nzchar(x)])
str(result)
List of 3
 $ Level1: chr [1:3] "a" "d" "e"
 $ Level2: chr [1:2] "b" "f"
 $ Level3: chr "c"

If it’s what you need.

You may consider also to avoid a for loop to have lst1:

lst1 <- split(t(df), rownames(t(df)))
# Then apply the code above.
result <- lapply(lst1, function(x) x[nzchar(x)])

With data:

df <- structure(list(Level1 = c("a", "d", "e"), Level2 = c("b", "", 
"f"), Level3 = c("c", "", "")), class = "data.frame", row.names = c(NA, 
-3L))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading