Reputation: 593
I want to make a function to loop through the rows of specific columns and assign the output of each column into new column. In this instance I want to loop through ctV1 and ctV2 to samples2to9 and samples11to18.
I was thinking if this:
RNAcopy<- function(for i in x {10^((i - 45.61196)/(4.229))})
dfqpcr$samples2to9 <- RNAcopy(dfqpcr[,4], na.rm=TRUE)
dfqpcr$samples11to18 <- RNAcopy(dfqpcr[,5], na.rm=TRUE)
My data dput:
structure(list(X = c(4000, 40000, 4e+05, 4e+06, 4e+07, 4e+08,
NA, NA), X.1 = c(3.602059991, 4.602059991, 5.602059991, 6.602059991,
7.602059991, 8.602059991, NA, NA), X.2 = c(24L, 48L, 72L, 96L,
24L, 48L, 72L, 96L), ctV1 = c(22.92, 24.29, 24.29, 27.91, 21.44,
16.5, 17.79, 17.34), ctV2 = c(24.21, 22.16, 22.16, 23.76, 22.81,
18.31, 16.56, 19.09), ctSTD = c(33L, 28L, 24L, 20L, 15L, 12L,
NA, NA), X.3 = c(NA, NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA,
8L), class = "data.frame")
How to make a function that does this task?
Upvotes: 0
Views: 81
Reputation: 2954
for iteration, you can use base apply
or alternatively, the map
functions (in the {purrr} package) to do the iteration, and then force the output to the format you want (vector) and assign the results.
# modify the function
RNAcopy <- function(x) {10^((x - 45.61196)/4.220)}
# base version- need to unlist to make it a vector
unlist(lapply(data$ctV1, FUN = RNAcopy))
I typically use the purrr
version so that I can ensure the result fits the format I want:
# purrr version, to force to vector format
purrr::map_dbl(data$ctV1, ~RNAcopy(.x))
then you can assign to new column/variable as you did above.
For your example- the function alone will be applied to each value in your vector:
RNAcopy(data$ctV1)
Upvotes: 1
Reputation: 1378
If you really want to loop through (unadvised) then you can just define the function:
RNAcopy = function(x) 10^((x - 45.61196)/4.229)
Now you can loop through and create your new columns, but you'll have to decide how you want to name them.
for (i in 4:5) {
name <- paste0('new_column_', i)
dfqpcr[name] <- RNAcopy(dfpqcr[,i])
}
Upvotes: 0
Reputation: 507
From what we're seeing here, there's absolutely no need to loop through (as in; please don't)
Your work in R should be vectorized, if you want to take any sort of advantage of the language (and your processor).
For this, all you really need is the base assignment operator:
RNAcopy <- function(x) { 10^((x - 45.61196)/(4.229)) }
dfqpcr$samples2to9 <- RNAcopy(dfqpcr$ctV1)
dfqpcr$samples11to18 <- RNAcopy(dfqpcr$ctV2)
Upvotes: 2