no_one no_one - 1 month ago 11
R Question

lapply - assign specific value to other columns in the same row within data.frames

I have got a list with more than 100 data.frames, each one with 3 columns.

Here an example of one of the data.frames:

[[6]]
V1 V2 V3
2 12002
9 05 Jan 1974 404.074 2.940
10 12 Jan 1974 477.433 3.235
11 18 Jan 1974 443.135 3.099
12 30 Jan 1974 556.402 3.537
13 22 Nov 1974 534.586 3.455


What I desire to do is to copy the first row value on first column to the other two first row values in the other two columns.

My result, for all the data.frames contained in the list should be:

[[6]]
V1 V2 V3
2 12002 12002 12002
9 05 Jan 1974 404.074 2.940
10 12 Jan 1974 477.433 3.235
11 18 Jan 1974 443.135 3.099
12 30 Jan 1974 556.402 3.537
13 22 Nov 1974 534.586 3.455


n.b. the values to copy are different for each data.frame

I tried to do it first for one data.frame (without using
lapply
) and it actually works:

list[[1]]$V2[1] = list[[1]]$V1[1]


But when I try to do it by using the
lapply
function it doesn't work anymore:

list = lapply(list, function(x) x$V2[1] = x$V1[1])


What is wrong with my code?

Answer

You need to return the entire df after the assignment.

list <- lapply(list, function(x) {
    x[1,] <- x$V1[1]
    x
}