简体   繁体   English

将下面的单元格中的值添加到上面的单元格中

[英]Add the value from the cellbelow to the cell above

I guess this is an easy question, however I would appreciate help! 我想这是一个简单的问题,但是我将不胜感激! I want to add a value to the cell above. 我想为上面的单元格添加一个值。 Any suggestions? 有什么建议么?

 a <- c(0,"D",0,"E",0,"F")
 b <- c(0,"E",0,"F",0,"D")
 c <- cbind(a,b)
 c <- as.data.frame(c)
 c
 a b
 0 0
 D E
 0 0
 E F
 0 0
 F D

I want it to look like this:
 a b
 D0 E0
 D  E
 E0 F0
 E  F
 F0 D0
 F  D

You should be able to do that with a simple for loop: 您应该可以使用简单的for循环来做到这一点:

a <- c(0,"D",0,"E",0,"F")
b <- c(0,"E",0,"F",0,"D")
c <- data.frame(a, b, stringsAsFactors=FALSE)


for(row in seq(from=1, to=nrow(c), by=2)){

    c[row, ] <- paste0(c[row+1, ], c[row, ])
}

print(c)

#   a  b
#1 D0 E0
#2  D  E
#3 E0 F0
#4  E  F
#5 F0 D0
#6  F  D

Using dplyr , we can use lead to paste values from next rows where the row_number() is odd 使用dplyr ,我们可以使用lead来粘贴row_number()为奇数的下一行的值

library(dplyr)
df %>%
  mutate_all(~ifelse(row_number() %% 2 == 1, paste0(lead(.), .), .)) 

#   a  b
#1 D0 E0
#2  D  E
#3 E0 F0
#4  E  F
#5 F0 D0
#6  F  D

data 数据

Make sure you read data with stringsAsFactors = FALSE 确保使用stringsAsFactors = FALSE读取数据

a <- c(0,"D",0,"E",0,"F")
b <- c(0,"E",0,"F",0,"D")
df <- data.frame(a,b, stringsAsFactors = FALSE)

As with the other answers, I modified the as.data.frame call to have stringsAsFactors = F . 与其他答案一样,我将as.data.frame调用修改为具有stringsAsFactors = F

n_rows <- nrow(c)
c_changed <- c('a', 'b')

c[seq(1, n_rows, by = 2), c_changed] <- Map(paste0, c[seq(2, n_rows, by = 2), c_changed], c[seq(1, n_rows, by = 2), c_changed])

c

   a  b
1 D0 E0
2  D  E
3 E0 F0
4  E  F
5 F0 D0
6  F  D

Data: 数据:

a <- c(0,"D",0,"E",0,"F")
b <- c(0,"E",0,"F",0,"D")
c <- cbind(a,b)
c <- as.data.frame(c, stringsAsFactors = F)

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

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