简体   繁体   English

从循环函数中提取值以添加到列中

[英]Extract value from a loop function to add in columns

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).我想为我的每一列运行 NLSstAsymptotic 函数(示例数据表中的 X1:X3,我的真实数据表有更多的列和行)。

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?我怎么可能去做那件事?

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我们可以在tidyverse通过使用map循环列名来做到这一点,根据列名应用函数, select所需的列

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或者在带有lapplybase R通过循环遍历列

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

Consider building a matrix of values from NLSstAsymptotic with sapply across the x column names:考虑从NLSstAsymptotic构建一个值矩阵,其中sapplyx列名称:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM