I have a dataframe with the below structure and values:
我有一个dataframe,它的结构和值如下:
total_size <- 5000;
id line_number
1 1232
2 1456
3 1832
4 2002
I need to add a new column dynamically to the data frame with values from the next_row. ie: The new column value should be: (line_number) of next row -1. The value of the last row should be populated with the total_size value.
我需要用next_row的值动态地向数据框架添加一个新的列。ie:新的列值应该是:(line_number)下一行-1。最后一行的值应该用total_size值填充。
The final output I need to produce is:
我需要生产的最终输出是:
id line_number end_line_number
1 1232 1455
2 1456 1831
3 1832 2001
4 2002 5000
Any idea how I can generate this dynamically in R?
知道如何在R中动态生成这个吗?
1 个解决方案
#1
3
This is pretty basic question. You can create a new column by removing the first entry of the 2nd column, subtracting 1 from it and adding NA for the last entry.
这是一个非常基本的问题。您可以通过删除第二列的第一个条目、从中减去1并为最后一个条目添加NA来创建一个新列。
# assuming your data.frame is called 'dt'
dt$end_line_number <- c(dt$line_number[-1]-1, NA)
(or) using transform
(或)使用变换
dt <- transform(dt, end_line_number = c(line_number[-1]-1, NA))
#1
3
This is pretty basic question. You can create a new column by removing the first entry of the 2nd column, subtracting 1 from it and adding NA for the last entry.
这是一个非常基本的问题。您可以通过删除第二列的第一个条目、从中减去1并为最后一个条目添加NA来创建一个新列。
# assuming your data.frame is called 'dt'
dt$end_line_number <- c(dt$line_number[-1]-1, NA)
(or) using transform
(或)使用变换
dt <- transform(dt, end_line_number = c(line_number[-1]-1, NA))