*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))
Related
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)
I have a function that requires 4 parameters:
myFun <- function(a,b,c,d){}
I have a matrix where each row contains the parameters:
myMatrix = matrix(c(a1,a2,b1,b2,c1,c2,d1,d2), nrow=2, ncol=4)
Currently I have a loop which feeds the parameters to myFun:
m <- myMatrix
i <- 1
someVector <- c()
while (i<(length(m[,1])+1)){
someVector[i] <-
myFun(m[i,1],m[i,2],m[i,3],m[i,4])
i = i+1
}
print(someVector)
What I would like to know is there a better way to get this same result using sapply instead of a loop.
You can use mapply() here which allows you to give it vectors as arguments, you should turn your matrix into a dataframe.
df <- as.data.frame(myMatrix))
results <- mapply(myFun, df$a, df$b, df$c, df$d)
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))))
}
This question already has answers here:
How to subset from a list in R
(7 answers)
Closed 6 years ago.
Say I have a list, preds, that contains 3 different sets of predictions based on unique models.
set.seed(206)
preds <- list(rnorm(1:100), rnorm(1:100), rnorm(1:100))
I am having trouble iterating through the list and creating a new list. I want a list of new vectors that are composed of the corresponding index in the other vectors. So for example, I can get the first element in each vector of the list using sapply() like this:
sapply(preds, "[[", 1)
Which works well, but I cannot figure out how to iterate through each element in each vector to construct a new list. I want something like this (doesn't work):
sapply(preds, "[[", 1:100)
Using the above seed and preds list, my desired output would be something like:
first_element <- sapply(preds, "[[", 1)
second_element <- sapply(preds, "[[", 2)
third_element <- sapply(preds, "[[", 3)
desired_result <- rbind(first_element, second_element, third_element)
But for all elements in the list, which in this example is 100.
Please let me know if this is not clear, and I appreciate any help!
We need to use [
res <- sapply(preds, `[`, 1:3 )
all.equal(res, desired_result, check.attributes=FALSE)
#[1] TRUE
Here's an alternative approach:
nth_element <- function(dat, n){
res <- sapply(dat, "[[", n)
res
}
res2 <- do.call(rbind, lapply(c(1:3), function(x) nth_element(dat = preds, n = x)))
Borrowing akrun's check code:
all.equal(res2, desired_result, check.attributes=FALSE)
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)
}
)