简体   繁体   English

R:for循环中的cbind函数

[英]R: cbind function in for loop

c <- readline(prompt="Enter an integer: ")
b <- readline(prompt="Enter an integer: ")

for(i in 1:c){
assign(paste("a", i, sep = ""), i)
}

This gives a1, a2 ... ac variables containing 1,2 ... c 这给出a1,a2 ... ac变量,其中包含1,2 ... c

How can I use cbind based on the value of b? 如何根据b的值使用cbind? For example, take the following: 例如,采取以下措施:

# assume b = 3 and c = 12:

t1 <- cbind(a1,a2,a3)
t2 <- cbind(a4,a5,a6) 
t3 <- cbind(a7,a8,a9) 
t4 <- cbind(a10,a11,a12)

# assume b = 4 and c = 12:

t1 <- cbind(a1,a2,a3,a4)
t2 <- cbind(a5,a6,a7,a8)
t3 <- cbind(a9,a10,a11,a12)

Another example to clarify: assume b = 3, c=6 需要说明的另一个示例:假设b = 3,c = 6

a1 <- c(3,5,2)
a2 <- c(4,7,3)
a3 <- c(3,5,2)
a4 <- c(4,5,3)
a5 <- c(5,5,5)
a6 <- c(4,3,1)

t1 <- cbind(a1,a2,a3)
t2 <- cbind(a4,a5,a6)

Expected value of t1: t1的期望值:

3 4 3
5 7 5
2 3 2

I am making some assumptions about your data. 我正在对您的数据做一些假设。 I am assuming you have values assigned with the columns you are trying to cbind. 我假设您为尝试绑定的列分配了值。

a <- 12
b <- 3
test <- NULL
index <- NULL
for(i in 1:a){
 test[i] <- paste0("n_", i)
 index[i] <- paste(i)
}

start <- seq(1,a-b+1, by=b)
end <- seq(b,a, by=b)

s = list()
k=1
for(k in 1:length(start)){
cbind_list <- start[k]:end[k]
s[[k]] <- rbind(test[seq(cbind_list[1],cbind_list[length(cbind_list)],by=1)])
}
list_cols <- do.call(rbind, s)

n_1 <- rep(1,4)
n_2 <- rep(2,4)
n_3 <- rep(3,4)
n_4 <- rep(4,4)
n_5 <- rep(5,4)
n_6 <- rep(6,4)
n_7 <- rep(7,4)
n_8 <- rep(8,4)
n_9 <- rep(9,4)
n_10 <- rep(10,4)
n_11 <- rep(11,4)
n_12 <- rep(12,4)
df <- data.frame(n_1,n_2,n_3,n_4,n_5,n_6,n_7,n_8,n_9,n_10,n_11,n_12)

t=list()
for(p in 1:nrow(list_cols)){
nam <- paste0("t",p)
assign(nam,cbind(df[,match(list_cols[p,], colnames(df))]))
}

OUTPUT: 输出:

> t1
  n_1 n_2 n_3
1   1   2   3
2   1   2   3
3   1   2   3
4   1   2   3

UPDATED: 更新:

a <- 6
b <- 3
test <- NULL
index <- NULL
for(i in 1:a){
  test[i] <- paste0("n_", i)
  index[i] <- paste(i)
}

start <- seq(1,a-b+1, by=b)
end <- seq(b,a, by=b)

s = list()
k=1
for(k in 1:length(start)){
  cbind_list <- start[k]:end[k]
  s[[k]] <- rbind(test[seq(cbind_list[1],cbind_list[length(cbind_list)],by=1)])
}
list_cols <- do.call(rbind, s)

n_1 <- c(3,5,2)
n_2 <- c(4,7,3)
n_3 <- c(3,5,2)
n_4 <- c(4,5,3)
n_5 <- c(5,5,5)
n_6 <- c(4,3,1)

df <- data.frame(n_1,n_2,n_3,n_4,n_5,n_6)

t=list()
p=1
for(p in 1:nrow(list_cols)){
  nam <- paste0("t",p)
  assign(nam,cbind(df[,match(list_cols[p,], colnames(df))]))
}

OUTPUT: 输出:

> t1
  n_1 n_2 n_3
1   3   4   3
2   5   7   5
3   2   3   2

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

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