这就是我的df的样子,
Region Dummy value1 value2
Mangonui NA NA NA
Sales NA 9 6
Kaitaia NA NA NA
Sales NA 16 1
Whangaroa NA NA NA
Sales NA 2 2
重新生成此步骤的步骤
structure(list(Region = c("Mangonui", "Sales", "Kaitaia",
"Sales", "Whangaroa", "Sales"), Dummy = c(NA,
NA, NA, NA, NA, NA), Dweling_values = c(NA, "9", NA, "16", NA,
"2"), Section_values = c(NA, "6", NA, "1", NA, "2")), .Names = c("Region",
"Dummy", "value1", "value2"), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
如何将两行合并在一起,以便我可以获得针对地区名称的销售?所以输出应该是,
Region Dummy value1 value2
Mangonui NA 9 6
Kaitaia NA 16 1
Whangaroa NA 2 2
答案 0 :(得分:3)
base R
myNew <- cbind(df$Region[seq.int(1,nrow(df),2)], df[seq.int(2,nrow(df),2), 2:4])
names(myNew) <- names(df)
myNew
Region Dummy value1 value2
2 Mangonui NA 9 6
4 Kaitaia NA 16 1
6 Whangaroa NA 2 2
的更新强>
到目前为止,最优雅的解决方案是@thelatemail
cbind(df[1][c(TRUE,FALSE),,drop=FALSE], df[-1][c(FALSE,TRUE),])
Region Dummy value1 value2
1 Mangonui NA 9 6
3 Kaitaia NA 16 1
5 Whangaroa NA 2 2
答案 1 :(得分:2)
首先,你需要找到并责骂任何以这种形式提供数据的人。告诉他们,如果他们继续这样做,你就不会成为他们的朋友。然后,只使用一些简单的基本R函数:
# generate indices for the sales and region rows
sales_rows <- seq(2, nrow(df), by = 2)
region_rows <- seq(1, nrow(df), by = 2)
# subset to create the df you really want
sales_df <- df[sales_rows, ]
# use just the names from the region rows
regions <- df[region_rows, "Region"]
sales_df$Region <- regions
# > sales_df
# Region Dummy value1 value2
# 2 Mangonui NA 9 6
# 4 Kaitaia NA 16 1
# 6 Whangaroa NA 2 2
答案 2 :(得分:2)
使用dplyr
和tidyr
的解决方案。我们的想法是使用recode
将Sales
替换为NA
,使用fill
根据之前的行归置NA
,然后使用{{1}使用其他列中的任何非NA值过滤行。
filter_at