Pasting names to an object during lapply - r

Consider this code:
df <- as.data.frame(matrix(rnorm(9),3,3))
names(df) <- c("A","B","C")
y <- c(1,2,3)
list1 <- lapply(df, function(x) as.vector(x))
par(mfrow=c(1,3))
lapply(list1, function(x) plot(x,y))
I want to paste the name of each vector in list1 (A, B, C) to the x-axis of the respective x,y-plot.
Can i do it during lappy, or is it necessary to write a loop?

You can do it using 'lapply', while iterating over names:
lapply(names(list1),function(nn){
plot(list1[[nn]],y,ylab=nn)
}
)

Related

How can I multiply multiple dataframes of a list by each observation of a vector?

I have a list of dataframes that I would like to multiply for each element of vector.
The first dataframe in the list would be multiplied by the first observation of the vector, and so on, producing another list of dataframes already multiplied.
I tried to do this with a loop, but was unsuccessful. I also tried to imagine something using map or lapply, but I couldn't.
for(i in vec){
for(j in listdf){
listdf2 <- i*listdf[[j]]
}
}
Error in listdf[[j]] : invalid subscript type 'list'
Any idea how to solve this?
*Vector and the List of Dataframes have the same length.
Use Map :
listdf2 <- Map(`*`, listdf, vec)
in purrr this can be done using map2 :
listdf2 <- purrr::map2(listdf, vec, `*`)
If you are interested in for loop solution you just need one loop :
listdf2 <- vector('list', length(listdf))
for (i in seq_along(vec)) {
listdf2[[i]] <- listdf[[i]] * vec[i]
}
data
vec <- c(4, 3, 5)
df <- data.frame(a = 1:5, b = 3:7)
listdf <- list(df, df, df)

In R, how to read an index vector?

*Example.
I have two vectors, vec_1 and vec_2
vec_1 <- c(1,2,3,4)
ver_2 <- c(6,7)
I want to do
vec = vector()
for(i in 1:2){
vec[i] <- mean(vec_i)
}**
I already tested "paste" of various types. Help!*
We can use mget to get the values of the objects in a list, loop over the list with lapply, get the mean
lapply(mget(paste0("vec_", 1:2)), mean)
If it is a data.frame
lapply(mget(paste0('vec_', 1:10)), function(x) mean(x$Pressure))

rbind dataframes with varying names

I have a situation where I need to rbind multiple dataframes based on a name, the trouble i'm having is how to define binding on these dataframes when the names differ -
For instance, the names of my dataframes are:
AB_0
AB_1
BCD_0
BCD_1
And I want to rbind AB_0 and BCD_0, and AB_1 and BCD_1 - my common factor I'm binding on is everything from the _ and after
I know I could use strsplit, but all I'm trying to get to is something like:
for(i in 0:1){
do.call("rbind", mget(sprintf("*_%d", i)))
}
where * is some variable string with varying # of characters
Something like this?
AB_0 <- data.frame(a=1, b=1)
AB_1 <- data.frame(a=2, b=2)
BCD_0 <- data.frame(a=3, b=3)
BCD_1 <- data.frame(a=4, b=4)
XX0 <- do.call("rbind", mget(ls(pattern = ".+_0")))
XX1 <- do.call("rbind", mget(ls(pattern = ".+_1")))
Or automate using a list:
XX <- list()
for (i in 0:1) {
XX[[i+1]] <- do.call("rbind", mget(ls(pattern = paste0(".+_",i))))
}

R, apply function on every second column of a data frame?

How to apply a function on every second column of a data frame? That is to say, how to modify df2 <- sapply(df1, fun) such that df2 equals df1 but with fun applied to every second column? Here is what I tried:
a <- c(1,2,3,4,5)
b <- c(6,7,8,9,10)
df1 <- data.frame(a,b)
df2 <- sapply(df1[c(TRUE, FALSE)], function(x) x^2)
isTRUE(dim(df1)==dim(df2)) # FALSE
The problem with this code is, that it deletes all columns to which fun was not applied to (dim(df2) # 5 1).
Assigning variables to slices
You can assign new values for subsets of an object. Say for:
x <- c(1,2,3)
x[2] <- 4
Now x will be c(1,4,2). Similarly you can do this for row/columns of a matrix or dataframe. Here we use the apply function with the second argument 2 for cols (1 for cols). I recommend the seq function to generate a sequence of indices from=1, by=2 gives odd and from=2, by=2 gives even indices. Specifying this it way generalises to other subsets and straightforward to check you got it right.
a <- c(1,2,3,4,5)
b <- c(6,7,8,9,10)
df1 <- data.frame(a,b)
df2 <- df1
df2[,seq(1, ncol(df2), 2)] <- apply(df2[,seq(1, ncol(df2), 2)], 2, function(x) x^2)
Loops
Note that you can also do this with a loop:
df2 <- df1
for(col in seq(1, ncol(df2), 2)) df2[,col] <- sapply(df2[,col], function(x) x^2)
Vectorised functions
Since the squared operation is "vectorised" in R, in this case you could also do:
for(col in seq(1, ncol(df2), 2)) df2[,col] <- df2[,col]x^2
Or use vectorisation completely:
df2 <- df1
df2[,seq(1, ncol(df2), 2)] <- df2[,seq(1, ncol(df2), 2)]^2

Basic Loop through a matrix with pasting column names into result objects

I have a dataframe (samples x species) which I want to loop this command through (column-wise):
dist <- vegdist(decostand(X,"standardize",MARGIN=2), method="euclidean")
I need the name of the column in each of the new dist-values. So if my columns are called A, B, C, then the result should be dist-values called Dist.A, Dist.B, Dist.C, and so on. I believe this can be done with paste, but I have no clue how.
You can try (if it is a data.frame)
d1[] <- lapply(colnames(d1), function(x) paste(d1[,x], x, sep="."))
Or
d1[] <- Map(function(x,y) paste(x, y, sep="."), d1, colnames(d1))
If it is a matrix
m1[] <- paste(m1, colnames(m1)[col(m1)],sep=".")
data
m1 <- matrix(1:15, ncol=3, dimnames=list(NULL, LETTERS[1:3]))
d1 <- as.data.frame(m1)

Resources