R移动数据框的单元格以填充空单元格
R move the cells of a dataframe to fill in empty cells
在 R 中有没有办法创建这样的条件:
对于以下数据,如果第一列中的行为空,但该行中的其他列已填充,则将行向左移动以填充第一列。
例如,实际数据是这样的:
DIS1
area1 69284 178198 2.57
area2 9466 22586 2.39 NA
Total 78750 200784 2.55 NA
DIS2
area1 25008 69972 2.8
area2 23142 55587 2.4 NA
Total 48150 125559 2.61 NA
DIS3
area1 16240 37173 2.29
area2 66351 193612 2.92 NA
Total 82591 230785 2.79 NA
我希望数据看起来像这样:
DIS1
area1 69284 178198 2.57
area2 9466 22586 2.39 NA
Total 78750 200784 2.55 NA
DIS2
area1 25008 69972 2.8
area2 23142 55587 2.4 NA
Total 48150 125559 2.61 NA
DIS3
area1 16240 37173 2.29
area2 66351 193612 2.92 NA
Total 82591 230785 2.79 NA
我不确定如何为此写一些条件。如果有人能帮助我,我将不胜感激。
输出看起来像这样:
structure(list(a = structure(c(3L, 1L, 2L, 6L, 4L, 1L, 2L, 6L,
5L, 1L, 2L, 6L), .Label = c("", "area2", "DIS1", "DIS2", "DIS3",
"Total"), class = "factor"), b = structure(c(1L, 8L, 7L, 5L,
1L, 8L, 2L, 3L, 1L, 8L, 4L, 6L), .Label = c("", "23142", "48150",
"66351", "78750", "82591", "9466", "area1"), class = "factor"),
c = c(NA, 69284L, 22586L, 200784L, NA, 25008L, 55587L, 125559L,
NA, 16240L, 193612L, 230785L), d = c(NA, 178198, 2.39, 2.55,
NA, 69972, 2.4, 2.61, NA, 37173, 2.92, 2.79), e = c(NA, 2.57,
NA, NA, NA, 2.8, NA, NA, NA, 2.29, NA, NA)), .Names = c("a",
"b", "c", "d", "e"), class = "data.frame", row.names = c(NA,
-12L))
非常感谢
尝试
as.data.frame( t(apply(DIS1, 1, function(x)
if(x[1]=='') c(x[-1], x[1]) else x)))
在 R 中有没有办法创建这样的条件:
对于以下数据,如果第一列中的行为空,但该行中的其他列已填充,则将行向左移动以填充第一列。
例如,实际数据是这样的:
DIS1
area1 69284 178198 2.57
area2 9466 22586 2.39 NA
Total 78750 200784 2.55 NA
DIS2
area1 25008 69972 2.8
area2 23142 55587 2.4 NA
Total 48150 125559 2.61 NA
DIS3
area1 16240 37173 2.29
area2 66351 193612 2.92 NA
Total 82591 230785 2.79 NA
我希望数据看起来像这样:
DIS1
area1 69284 178198 2.57
area2 9466 22586 2.39 NA
Total 78750 200784 2.55 NA
DIS2
area1 25008 69972 2.8
area2 23142 55587 2.4 NA
Total 48150 125559 2.61 NA
DIS3
area1 16240 37173 2.29
area2 66351 193612 2.92 NA
Total 82591 230785 2.79 NA
我不确定如何为此写一些条件。如果有人能帮助我,我将不胜感激。
输出看起来像这样:
structure(list(a = structure(c(3L, 1L, 2L, 6L, 4L, 1L, 2L, 6L,
5L, 1L, 2L, 6L), .Label = c("", "area2", "DIS1", "DIS2", "DIS3",
"Total"), class = "factor"), b = structure(c(1L, 8L, 7L, 5L,
1L, 8L, 2L, 3L, 1L, 8L, 4L, 6L), .Label = c("", "23142", "48150",
"66351", "78750", "82591", "9466", "area1"), class = "factor"),
c = c(NA, 69284L, 22586L, 200784L, NA, 25008L, 55587L, 125559L,
NA, 16240L, 193612L, 230785L), d = c(NA, 178198, 2.39, 2.55,
NA, 69972, 2.4, 2.61, NA, 37173, 2.92, 2.79), e = c(NA, 2.57,
NA, NA, NA, 2.8, NA, NA, NA, 2.29, NA, NA)), .Names = c("a",
"b", "c", "d", "e"), class = "data.frame", row.names = c(NA,
-12L))
非常感谢
尝试
as.data.frame( t(apply(DIS1, 1, function(x)
if(x[1]=='') c(x[-1], x[1]) else x)))