Questions tagged [lapply]

lapply is a function in R that returns a list of the same length as given argument X, each element of which is the result of applying given function to the corresponding element of X

0
votes
1answer
19 views

Modifying specific elements in sublist without loop

I have a list of list which I am trying to modify in a particular way. The list of lists is organized similar to a matrix, but each element is a numerical vector. My goal is to update only a small ...
0
votes
0answers
15 views

Raycast function in r for sampling from a matrix between two points

I am trying to use R to calculate the mean and standard deviation of all pixels in a raster lying between two points. I have written a function that does something close to this, whereby I create a ...
0
votes
0answers
30 views

How can I search through excel files for a keyword using grep?

I need to iterate through the first few lines of a list of excel files & return the location of a certain keyword. What I have that's not working: # SampleFile is a list of 5 excel files ...
0
votes
2answers
33 views

Continue looping if address not found

AIM: I am trying to retrieve a series of maps using the get_map function from ggmaps. I know the following works when I use latitude and longitude: houses_maps <- lapply(latlon, ...
0
votes
1answer
23 views

lapply to unionSpatialPolygons in a list

I have a big list of SpatialPolygonsDataFrame objects I created using lapply and gdal_polygonizeR (code here: https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) on a ...
0
votes
1answer
7 views

Lappy with while function

I have a list of datasets, I need to change the variable names. Some characters (i.e. ".") are repeated. I want to get rid of them neatly combining a while loop and an aptly created function. Both ...
1
vote
3answers
58 views

How to use lapply to transform specific values in a list of dataframes

I'm looking for help to transform a for loop into an lapply or similar function. I have a list of similar data.frames, each containing an indicator column ('a') a value column ('b') I want to ...
0
votes
1answer
14 views

remove rasters with 'NA' values after batch reclassify in R

I used to for loop to iterate thru a bunch of rasters (n=533) and reclassify them based on converting certain values (less than 353.3) to 'NA'. I would now like to have an efficient way to search thru ...
0
votes
1answer
19 views

lapply to convert rasters to polygons using gdal_polygonizeR

I am using John Baumgrtner's gdal_polygonizeR (https://johnbaumgartner.wordpress.com/2012/07/26/getting-rasters-into-shape-from-r/) to covert rasters to polygons in R. Aside - I tried raster pkg ...
0
votes
3answers
25 views

display ids of all values of a particular column is NA r

id <- c(1,1,1,2,3,3,3,4,4,5,5) val1 <-c(NA,1,2,NA,NA,3,4,4,NA,NA) dt <- data.frame(id,val1) dt being my dataframe i want to output the id which has all val1 as NA. id val1 1 NA 1 1 1 2 2 ...
0
votes
1answer
26 views

Replacement of loops with if statement in R

Hi what would be the best way of doing following loops in R? for (i in 1:nrow(df1)) { counter <- 0 for (j in 1:nrow(df2)) { if (df2$x[j] >= df1$a[i] & df2$x[j] < df1$b[i]{counter ...
3
votes
1answer
64 views

Fast list generation from the narrow data.frame

I have a data.frame in the narrow format like that: test_data<-data.frame(id=rep(1:200,50), variable=sample(LETTERS,10000,T), value=sample(letters,10000,T), stringsAsFactors = F) I want to get ...
1
vote
2answers
36 views

Mean of columns of different dataframes in r

df1 <- data.frame(id=c(1,2,3,4,5,6),val1=c(1,2,3,NA,NA,6)) df2 <- data.frame(id=c(3,4,7,6,8) , val1=c(1,2,3,4,5)) Now what want is to combine the values of val1 from df1 and df2 as mean values ...
0
votes
1answer
20 views

Saving deeply nested files to specific directories with specific filenames

Given a 3 level nested list: mylist <- list("1000"=list("cars"=list("fast"=mtcars[1:10,], "slow"=mtcars[11:15,]), "flower"=iris), "2000"=list("tooth"=ToothGrowth, "air"=airquality, "cars"=list("...
-1
votes
2answers
22 views

R data.table use if statement in lapply

I would like to convert some columns from numbers to date format; and I'm thinking about using the following code: colList <- c("Date1","Date2") dataDT[, (colList) := lapply(.SD, function(x){ if ...
1
vote
2answers
28 views

Conditionally append dataframes to specific levels of a nested list

I have a nested list (mylist), and I would like to cbind a dataframe (colors) automatically to a lower level list (iris) only if the name of the list contains a specific string (iris), but I'm running ...
0
votes
1answer
20 views

List containing data tables - Unable to use a function to rename columns?

I have 20 excel files containing city level data for each year. I imported them in a list because I thought it will be easier to loop over them. The first task that I wanted to do is to change the ...
0
votes
2answers
55 views

How to use a list of row numbers to look up values in a dataframe column

I have a big dataframe containing to columns, one that is an ID Code named "code" and one that is the name of two train stations separated by a slash named "name" I wanted to search all the codes ...
-2
votes
1answer
25 views

Using tapply on a list of data frames

I would like to use tapply on a list of data frames in oder to calculate sums for individual groups and then tabulate the occurence of the value 0. On an individual data frame I would do this: sums &...
3
votes
1answer
46 views

functions in R, without specifying data

I have the following data: x <- 11 w <- "12AAB" y <- "var1" I also have a function funky(x,w,y){} With the above 3 constants as inputs I can apply the following: funky(x = x, w = w, y = y)...
0
votes
1answer
26 views

Sum across selected columns in a list

x <- list(a = matrix(c(rep(1, times = 8), 9:16), nc = 4), b = matrix(1, nc = 4, nr = 4)) My data share the 1st and 2nd column while the 3rd and 4th column is different If I want to add the ...
0
votes
1answer
16 views

New variable from list.file

I am creating an object calling all .csv files in a directory, reading them in according to some specifications, and merging them. Before merging them I want to take the first two letters of the ...
0
votes
1answer
31 views

Sum last value in a dataframe in list A to first value in dataframe in list B

I have two lists that contain 500 data frames. Here is an example of two lists containing 2 data frames each. l1 [[1]] X1 X2 X3 1 1 0 0 2 5 1 8 [[2]] X1 X2 X3 ...
0
votes
1answer
60 views

Convert my simple 'for loop' into an apply function

I'm trying to embrace the apply family more, but still having trouble. I mostly understand simple cases with lapply (as below), but am having issues with more complicated apply functions. I have a ...
2
votes
2answers
34 views

Multiple list nesting with split(), R

Given a dataset with multiple unique elements in a column, I'd like to split those unique elements into new dataframes, but have the dataframe nested one level down. Essentially adding an extra level ...
0
votes
1answer
54 views

R: Fastest way to residualize hundreds of variables

I have a large data set (~30m observations, ~800 variables) and I need to residualize 700 variables by regressing each of them on 3 variables and then storing the residuals. Here is what I am ...
0
votes
0answers
29 views

how to reclassify a batch of rasters in R

I am trying to run the same reclassify on a bunch of raster (.tif) files in R. I followed the example from the following code: wfrastlist <- list.files(path = "/path/to/...
1
vote
3answers
24 views

how to efficiently import multiple raster (.tif) files into R

I am an R novice, especially when it comes to spatial data. I am trying to find a way to efficiently import multiple (~600) single-band raster (.tif) files into R, all stored in the same folder. Not ...
-2
votes
0answers
26 views

Get data from another dataframe using apply function in R [duplicate]

I have two data frames like below: Long ID STATUS CREATETIME 1 AUTO-CLOSED 1538919900835 1 CLOSED 1538919900835 1 CONFIRMED 1538919900835 2 TRACKING 1538919900837 2 AUTO-...
0
votes
0answers
32 views

Lapply for multiple elements within in list R (maybe loop?)

I have the following code which extracts tables from 9 pdf documents and produces a list with 9 elements. library(tabulizer) files <- dir(path =".", pattern ="\\.pdf$", full.names = TRUE, ...
0
votes
0answers
7 views

Why do I get NA even if I used na.rm=“TRUE”?

Could you please help me why I still get an NA even if I used lapply(HiringDateInfo$YrsEmp,mean,na.rm ="TRUE")? > lapply(HiringDateInfo$YrsEmp,mean,na.rm ="TRUE") [[1]] [1] NA [[2]] [1]...
1
vote
1answer
48 views

How should I vectorize this simple for loop in R?

The loop to be vectorized: n = 1000000 x = numeric(n) for (I in 1:n) x[i] = rpois(1, 3) + rpois(1, 5) The original is just too slow, I don't have much experience with for loops or the apply ...
0
votes
1answer
29 views

Pass dataframe function to gstat formula argument

I'm trying to create inverse distance weighted rasters using gstat() and raster::interpolate(). I'm running into issues passing a column name to the formula argument of the gstat function. Hardcoding ...
0
votes
0answers
11 views

Merging folder of .txt files into one .csv file using R

I am trying to get a structural topic modeling done. Therefore I am trying to combine a large amount of txt files (which are newspaper articles) into one csv file, to then proceed with the structural ...
0
votes
2answers
27 views

R Dplyr and string values, how to split and get the second element? vapply/sapply

Been having difficulty with this one data frame manipulation in R. I have two columns for well height and a date-time string ("yyyy-mm-dd HH:MM:ss"). I would like to extract all the rows from this ...
2
votes
2answers
55 views

generate random number with varying parameters using lapply in R

I need to generate random numbers (binomial) with varying parameters. I am trying to do that using lapply function. This is my code so far: lst1 <- list(n=c(10,20), size=c(100,200), q=c(0.1,0.2)...
0
votes
1answer
23 views

How do you use lapply on two variables in a Shiny app?

I have the following chunk of code: observeEvent(subsettedData(), { lapply(col_names, function(var) { selections <- unique(subsettedData()[[var]]) if (length(input[[var]]) == 0) ...
0
votes
0answers
7 views

Repeated lappy, how to simplf

What would be the best way to make this code more elegant and get rid of all the repated parts? Each indicies corresponds to one of 9 elements in a list and I can't figure out how to do a for loop. ...
0
votes
1answer
23 views

How to build and loop through a group of expressions referencing environment objects (without list structure)? [R]

I want to simplify the below in functional form: write_file(s01e01, 's01e01.txt') write_file(s01e02, 's01e02.txt') write_file(s01e03, 's01e03.txt') write_file(s02e01, 's01e01.txt') ... ...
-5
votes
1answer
29 views

Creating a list of multiple excel files that have been converted to dataframes [closed]

I have 4 excel files in the one folder on my computer. The files contain both alphanumeric and numeric data. I want to write a function to sequentially read each xlsx file, convert it to a dataframe, ...
1
vote
2answers
27 views

Applying RSI function to a list of Dataframes

I have created a list of data frames of the closing prices of all of the S&P 500 companies. I would like to calculate RSI for each company. library(BatchGetSymbols) first.date <- Sys.Date()-...
1
vote
2answers
29 views

Using tryCatch to skip execution upon error without exiting lapply()

I am trying to write a function that cleans spreadsheets. However, some of the spreadsheets are corrupted and will not open. I want the function to recognize this, print an error message, and skip ...
0
votes
1answer
32 views

Iterative Algorithms Using Apply family: Metropolis-Hasting Alg

In algorithm building we often need both the previous and current iteration values. I am trying to leverage the apply family to improve the speed of the algorithm. I have built the Metropolis-Hasting ...
2
votes
2answers
64 views

Converting R list to dataframe with recycled vector elements [duplicate]

It's been some time since I've worked in R, so I'm a little rusty and need some help with lists. I have a list which contains 7 elements that pertain to patrons' purchases while visiting a large ...
1
vote
2answers
37 views

How to rename dataframes in list based on values in their columns with lapply

I have a list of dataframes x with column V1 that says the country and V2 that says the year. The names of the dataframes are y1, y2, y3 and so on. I want to rename them so that they show the country ...
0
votes
2answers
53 views

Call apply-like function on two rows to match

I have a dataframe with multiple rows. I want to call a function is using any two rows. For example, Let's say I have this data and this myFunc which accepts two args: df <- data.frame(q1=c(1,2,5),...
0
votes
1answer
17 views

removing covariates from a linear mixed model using update

I'm newish to R. I have a linear mixed model with several predictors and I want to test the significance of each of them. I know that I could use lmerTest but my co-authors want me to do a likelihood ...
0
votes
1answer
24 views

How to avoid null values in a FOR loop to handle list objects in R

I want to produce summary statistics using a for loop in a batch. #--Zone statistics zone <- lapply(YieldPts, function(a){extract(NewDatasetRaster[[11]], a)}) # extract zone variable by points ...
1
vote
3answers
48 views

apply regexp and update column across data frames

I have two data frames --- table A is the pattern table with reference names, and table B is the old name table. I want to subset table B, where it matches the pattern in table a, and when the cell ...
1
vote
2answers
32 views

apply regexp in one data frame based on the column in another data frame

I have two data frames --- table A is the pattern table, and table B is the name table. I want to subset table B, where it matches the pattern in table a. A <- data.frame(pattern = c("aa", "bb", "...