Extract value from a loop function to add in columns

205 views Asked by At

I would like to run the NLSstAsymptotic function for each of my columns (X1:X3 in the example data sheet, my real data sheet has many more columns and rows).

ID<-c(1,2,3,4,5,6,7,8,9,10,11,12,13)
X1<-c(0,1,2,4,5,5,6,7,8,9,10,10,11)
X2<-c(0,1,2,3,4,5,6,7,8,8,9,10,10)
X3<-c(0,1,2,3,4,4,5,6,7,8,9,10,11)
df<-data.frame(ID,X1,X2,X3)

df_new <- sortedXyData(expression(ID), expression(X1), data=df)
NLSstAsymptotic(df_new)

The desired result should take the following form:

b1
-1.31
-1.41
-0.84

How could I go about to do that?

2

There are 2 answers

0
Parfait On BEST ANSWER

Consider building a matrix of values from NLSstAsymptotic with sapply across the x column names:

asym_matrix <- sapply(names(df)[-1], function(x_col) 
                      NLSstAsymptotic(sortedXyData(ID, x_col, data=df)))

asym_matrix

#            X1        X2            X3
# b0  -1.311894 -1.418423 -8.461552e-01
# b1  24.513630 22.280853  5.063632e+12
# lrc -2.929047 -2.856312 -2.936952e+01


t(asym_matrix)                                # TRANSPOSED VERSION
data.frame(t(asym_matrix))                    # DATA FRAME VERSION

#            b0           b1        lrc
# X1 -1.3118945 2.451363e+01  -2.929047
# X2 -1.4184228 2.228085e+01  -2.856312
# X3 -0.8461552 5.063632e+12 -29.369516
0
akrun On

We can do this in tidyverse by looping over the column names with map, apply the functions based on the column names, select the required column

library(dplyr)
library(purrr)
map_dfr(names(df)[2:4],
     ~NLSstAsymptotic(sortedXyData(ID, .x, data = df))) %>%
   select(b1)
# A tibble: 3 x 1
#       b1
#    <dbl>
#1 2.45e 1
#2 2.23e 1
#3 5.06e12

Or in base R with lapply by looping over the columns

do.call(rbind, lapply(df[-1], function(x) 
    NLSstAsymptotic(sortedXyData(expression(ID), expression(col), 
        data = cbind(df['ID'], col = x)))[2]))