简体   繁体   中英

R: create column with the values of another column -1

I have a table in R containing n values. I want to create a column B , which has the values of another column A , but moved them "up" 1 line:

Example:

A    B
_    _
1    2
2    3
3    n
n    n

I know that the first item of A will be deleted in column B and also I would like to duplicate the value n and move it to the last "empty" spot of B (which would otherwise be 0 because I moved all values "up")

dat <- data.frame(A = c(1, 2, 3, 4))
dat$B <- dat$A[c(2:length(dat$A), length(dat$A))]

Should work.

df1$B <- with(df1,c(tail(A,-1),tail(A,1)))

Sample data:

df1 <- data.frame(A = c(1, 2, 3, 0))

Output:

#> df1
#  A B
#1 1 2
#2 2 3
#3 3 0
#4 0 0

您可以简单地将值替换为

table$B[1:n-1] <- table$A[2:n]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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