0

我想为我的每一列运行 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)

期望的结果应采用以下形式:

b1
-1.31
-1.41
-0.84

我怎么能这样做呢?

4

2 回答 2

1

我们可以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

或者通过在列base R上循环lapply

do.call(rbind, lapply(df[-1], function(x) 
    NLSstAsymptotic(sortedXyData(expression(ID), expression(col), 
        data = cbind(df['ID'], col = x)))[2]))
于 2020-02-02T16:10:45.213 回答
1

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
于 2020-02-02T16:31:51.573 回答