Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将行添加到数据帧_R_Rows - Fatal编程技术网

R 将行添加到数据帧

R 将行添加到数据帧,r,rows,R,Rows,我有这样一个df: x <- data.frame("Year" = c(1945,1945,1946,1946,1947,1947), "Age" = c(1,2,1,2,1,2), "Value" = c(4,5,4,5,4,6)) x <- data.frame("Year" = c(1945, 1945,1945,1945,1946,1946,1946,1946,1947,1947,1947,1

我有这样一个df:

x <- data.frame("Year" = c(1945,1945,1946,1946,1947,1947), "Age" = c(1,2,1,2,1,2), "Value" = c(4,5,4,5,4,6))
x <- data.frame("Year" = c(1945, 1945,1945,1945,1946,1946,1946,1946,1947,1947,1947,1947), "Age" = c(1,1,2,2,1,1,2,2,1,1,2,2), "Value" = c(4,3,5,4,4,3,5,4,4,3,5,4))
#original df
x <- data.frame("Year" = c(1945,1945,1946,1946,1947,1947), "Age" = c(1,2,1,2,1,2),"Value" = c(4,5,4,5,4,6))

#replicate df with value minus 1
y <- data.frame(x[,c("Year", "Age")], Value = x[,"Value"] -1)

#combine
z <- rbind(x,y)

x您可以这样做:

x <- data.frame("Year" = c(1945,1945,1946,1946,1947,1947), "Age" = c(1,2,1,2,1,2), "Value" = c(4,5,4,5,4,6))
x <- data.frame("Year" = c(1945, 1945,1945,1945,1946,1946,1946,1946,1947,1947,1947,1947), "Age" = c(1,1,2,2,1,1,2,2,1,1,2,2), "Value" = c(4,3,5,4,4,3,5,4,4,3,5,4))
#original df
x <- data.frame("Year" = c(1945,1945,1946,1946,1947,1947), "Age" = c(1,2,1,2,1,2),"Value" = c(4,5,4,5,4,6))

#replicate df with value minus 1
y <- data.frame(x[,c("Year", "Age")], Value = x[,"Value"] -1)

#combine
z <- rbind(x,y)
当然,上面的代码可以缩短,例如在直接更新dataframe x时

x <- rbind(x, data.frame(x[,c("Year", "Age")], Value = x[,"Value"] -1))
这是否有效:

library(dplyr)
x %>% inner_join(x %>% select(1)) %>% group_by(Year, Age) %>% 
mutate(Value = case_when(row_number() == 2 ~ Value - 1, TRUE ~ Value))
Joining, by = "Year"
# A tibble: 12 x 3
# Groups:   Year, Age [6]
    Year   Age Value
   <dbl> <dbl> <dbl>
 1  1945     1     4
 2  1945     1     3
 3  1945     2     5
 4  1945     2     4
 5  1946     1     4
 6  1946     1     3
 7  1946     2     5
 8  1946     2     4
 9  1947     1     4
10  1947     1     3
11  1947     2     6
12  1947     2     5

base
中,您可以将每行重复两次,并将回收的
0:-1
添加到
值中

within(x[rep(1:nrow(x), each = 2), ], Value <- Value + 0:-1)

他们都给出了以下结论。输出的顺序很好,因此不需要使用
order()
arrange()


我不太了解你的情况,你能澄清一下吗?例如,为什么第3行中的
5
在您想要的输出中?您可以试试这个:
library(tidyverse)

x %>%
  uncount(2) %>% 
  mutate(Value = Value + 0:-1)
   Year Age Value
1  1945   1     4
2  1945   1     3
3  1945   2     5
4  1945   2     4
5  1946   1     4
6  1946   1     3
7  1946   2     5
8  1946   2     4
9  1947   1     4
10 1947   1     3
11 1947   2     6
12 1947   2     5