Cbhihe
Cbhihe

Reputation: 531

Modify dataframes in list with R

I want to work on columns and row-names of a bunch of data frames, say W1, W2, W3, whose names are listed in a previously built list, say W. I've seen quite a few similar questions, but none seem to address my difficulty:

>  W <- list(W1, W2, W3)
>  lapply(W, is.data.frame)
$W1
[1] TRUE
$W2
[1] TRUE
$W3
[1] TRUE

Ultimately what I want to do is:

>  lapply(W, function(x) rowname(x) = x[,1])
>  lapply(W, function(x) x = x[,-1])

but in both cases I get the content of the first column for each data frame. I'm missing something basic...

Upvotes: 1

Views: 2681

Answers (2)

Taiki Sakai
Taiki Sakai

Reputation: 311

Just combine the two steps into one lapply. Remember that in R a function will return the last thing it evaluates, so in your first lapply it is just going to return the rownames of each data.frame since that's the last thing the function did. Adding x[,-1] after that makes it return the modified data.frame, minus the first column.

W1 <- data.frame(a=letters[1:3], b=1:3, c=4:6)
W2 <- data.frame(a=letters[4:5], b=4:5, c=5:6)
W3 <- data.frame(a=LETTERS[1:5], b=1:5, c=11:15)
W <- list(W1, W2, W3)

W <- lapply(W, function(x) {
    row.names(x) <- x[,1]
    x[,-1]
})

Upvotes: 5

moodymudskipper
moodymudskipper

Reputation: 47300

With tidyverse using @Taiki-Sakai's data:

library(tidyverse)
map(W, column_to_rownames, "a") # use remove_rownames(W) if relevant
# [[1]]
#   b c
# a 1 4
# b 2 5
# c 3 6
# 
# [[2]]
#   b c
# d 4 5
# e 5 6
# 
# [[3]]
#   b  c
# A 1 11
# B 2 12
# C 3 13
# D 4 14
# E 5 15
# 

Upvotes: 1

Related Questions