D Schiff
D Schiff

Reputation: 101

Replacing values in a list of data frames

I have a list of data frames. Each has an ID column, followed by a number of numeric columns (with column names).

I would like to replace all the 1's with 0's for all the numeric columns, but keep the ID column the same. I can do this in part with a single data frame using

 df[,-1] <- 0

But when I try to embed this in lapply, it fails:

df2 <- lapply(df, function(x) {x[,-1] <- 0})

I've tried using subset, ifelse, while, mutate, but struggling with this simple replacement. Could recreate the data frames from scratch, or recombine the ID column at the end, but this strikes me as something that should be easy...

Test list:

test_list <- list(data.frame("ID"=letters[1:3], "col2"=1:3, "col3"=0:2), data.frame("ID"=letters[4:6], "col2"=4:6, "col3"=0:2))

The end result should be:

final_list <- list(data.frame("ID"=letters[1:3], "col2"=0, "col3"=0), data.frame("ID"=letters[4:6], "col2"=0, "col3"=0))

Upvotes: 1

Views: 2225

Answers (2)

Mako212
Mako212

Reputation: 7292

Your question is worded a little bit strangely in that it sounds like you want to replace all the 1's with 0's, but your example seems to contradict that.

If you want to replace just 1's with 0's, you could do so like this:

lapply(df, function(x) {x[x==1] <- 0; return(x)})

[[1]]
  ID col2 col3
1  a    0    0
2  b    2    0
3  c    3    2

[[2]]
  ID col2 col3
1  d    4    0
2  e    5    0
3  f    6    2

Upvotes: 2

www
www

Reputation: 39154

Add return(x) to your function and then it should work fine.

lapply(test_list, function(x){
  x[, -1] <- 0
  return(x)
})
# [[1]]
#   ID col2 col3
# 1  a    0    0
# 2  b    0    0
# 3  c    0    0
# 
# [[2]]
#   ID col2 col3
# 1  d    0    0
# 2  e    0    0
# 3  f    0    0

Upvotes: 2

Related Questions