1

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])
  • defines row-names for each data-frame using its first column values.
  • suppress the first column after that,

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

Cbhihe
  • 511
  • 9
  • 24

2 Answers2

5

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]
})
Cbhihe
  • 511
  • 9
  • 24
Taiki Sakai
  • 311
  • 1
  • 5
  • 1
    Tx. I took the liberty to edit your answer in order to make it a working solution. **1/** typo in x[,-1] which you wrote as [x,-1] and **2/** added assignment to W as W <- lapply( ... ) to make changes definitive. – Cbhihe Nov 15 '18 at 10:02
1

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
# 
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • Hi Antoine and tx. Yr proposed solution works but why bring in yet another package when you can do that with base package tools at only a slightly greater typing cost... Thriftiness rules. – Cbhihe Nov 15 '18 at 10:28
  • 2
    You're absolutely right that you shouldn't attach a new package for a quick task that can be done in base R. However these small tasks are usually part of a bigger project. If overall you see value in purrr and attach it for a given project, this solution is a compact and readable alternative so I believe some may find value in it. – moodymudskipper Nov 15 '18 at 10:37