简体   繁体   English

如何在 R 中从第二行开始将值从一列复制到另一列

[英]How can I copy values from one column to another starting on the second row, in R

I'm trying to copy values from one column to a new column in R, starting from the second column onwards.我正在尝试将值从一列复制到 R 中的新列,从第二列开始。

I've tried df$B <- df$A[-1,] but since it eliminates one of the values, the column will not have the same length anymore.我已经尝试过df$B <- df$A[-1,]但由于它消除了其中一个值,因此该列将不再具有相同的长度。

Ie, what I need is the following (create column B based on column A).即,我需要的是以下内容(基于 A 列创建 B 列)。

   A  B
1  a  b
2  b  c
3  c  d
4  d  e
5  e  f
6  f  g
7  g  h
8  h  i
9  i  j
10 j  NA

You can use any of the option below:您可以使用以下任何选项:

df$B <- dplyr::lead(df$A)
df$B <- data.table::shift(df$A, type = "lead")
df$B <- c(tail(df$A, -1), NA)
df$B <- c(df$A[-1], NA)

We can also do我们也可以做

df <- transform(df, B = c(A[-1], NA))

暂无
暂无

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

相关问题 (R) 如何根据 R 中的另一列和 ID 从一列复制粘贴值 - (R) How to copy paste values from one column based on another column and ID in R 将唯一值从一列复制到另一列 - Copy unique values from one column to another R 在 R 中,当替换列不为空时,如何将一列中的值替换为另一列的值? - In R, how can I replace the values in one column with the values of another column whenever the replacing column is not empty? 如何使用R data.table将值从一行和一列(“单元格”)复制(“结转”)到不同的行和列? - How to copy (“carry forward”) values from one row and column (“cell”) to a different row and column with R data.table? 如何在匹配R中的其他列时将特定值从一个数据列复制到另一个数据列? - How to copy specific values from one data column to another while matching other columns in R? 如何将行从一个 data.frame 复制到另一个 [R] - How to copy row from one data.frame in to another [R] 如何计算一个数据帧中的值并将结果传输到 R 中相应列下的第二个数据帧? - How can I count values in one dataframe and transfer the results to a second dataframe under the corresponding column in R? 使用R将一列中的值添加到第二列中缺少值的另一列 - Adding values from one column to another with missing values in the second column using R 从 R dataframe 中的特定行将数据从一列复制到另一列 - Copy data from one column to another column from a specific row in R dataframe 如何使用 R 将某些数据从一个 csv 文件复制到另一个 csv 文件? - How can I copy certain data from one csv file to another csv file using R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM