【问题标题】:filling a dataframe or matrix with for loop用 for 循环填充数据框或矩阵
【发布时间】:2014-11-21 07:58:14
【问题描述】:

有没有一种快速的方法可以用n1 然后n2 最后n3 的值从左到右填充这个矩阵df

df=matrix(, nrow = 3, ncol =3)
rownames(df)<- c("1","2","3")
colnames(df)<- c("A", "B", "C")
n1= seq(1:3)
n2= seq(6:8)
n3= seq(10:12)

【问题讨论】:

  • df[] &lt;- cbind(n1, n2, n3)? (另外,我不认为seq(6:8) 做你认为它做的事情......

标签: r for-loop matrix dataframe


【解决方案1】:

如果您有很多列到cbind,一种方法是:

df[] <- do.call(cbind,mget(ls(pattern="n\\d+"))) #here I am assuming that all the objects created follow the pattern `n1`, `n2`, `n3` etc.

df
#  A B  C
#1 1 6 10
#2 2 7 11
#3 3 8 12

如果您填写的是data.frame,例如df1

 df1[] <- mget(ls(pattern="n\\d+"))
 df1
 #  A B  C
 #1 1 6 10
 #2 2 7 11
 #3 3 8 12

数据

 df <- matrix(, nrow = 3, ncol =3)
 rownames(df)<- c("1","2","3")
 colnames(df)<- c("A", "B", "C")

 df1 <- as.data.frame(df)
 n1 <- 1:3
 n2 <- 6:8
 n3 <- 10:12

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多