我有一个数据帧,其中X1
列(即地址)的第二行应移至其上一行的x3
列。下面是actaul数据帧结构。如何在r
中做到这一点。
structure(list(X1 = c("(512) Brewing Company", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"0 Mile Brewing Company", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"10 Barrel Brewing", "1501 E StSan Diego, California, 92101United States"
), X2 = c("(512) Brewing Company", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"0 Mile Brewing Company", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"10 Barrel Brewing", "1501 E StSan Diego, California, 92101United States"
), X3 = c("-", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"-", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"-", "1501 E StSan Diego, California, 92101United States"), X4 = c("-",
"407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"-", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"-", "1501 E StSan Diego, California, 92101United States"), X5 = c("3.84",
"Brewery, Bar", "-", "Brewery", "-", "Brewery, Bar, Eatery"),
X6 = c("37", "Brewery, Bar", "4", "Brewery", "0", "Brewery, Bar, Eatery"
)), row.names = 4:9, class = "data.frame")
答案 0 :(得分:1)
假设您的行数总是偶数-
df <- structure(list(X1 = c("(512) Brewing Company", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"0 Mile Brewing Company", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"10 Barrel Brewing", "1501 E StSan Diego, California, 92101United States"
), X2 = c("(512) Brewing Company", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"0 Mile Brewing Company", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"10 Barrel Brewing", "1501 E StSan Diego, California, 92101United States"
), X3 = c("-", "407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"-", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"-", "1501 E StSan Diego, California, 92101United States"), X4 = c("-",
"407 Radam LnSte F200Austin, Texas, 78745-1197United States(512) 921-1545",
"-", "11 W 2nd StHummelstown, Pennsylvania, 17036-1506United States(717) 319-0133",
"-", "1501 E StSan Diego, California, 92101United States"), X5 = c("3.84",
"Brewery, Bar", "-", "Brewery", "-", "Brewery, Bar, Eatery"),
X6 = c("37", "Brewery, Bar", "4", "Brewery", "0", "Brewery, Bar, Eatery"
)), row.names = 4:9, class = "data.frame")
df$X3 <- NA_character_
df$X3[seq(1, nrow(df), by = 2)] <- df$X1[seq(2, nrow(df), by = 2)]
使用dplyr
包的另一种通用方法(与行数无关)-
library(dplyr)
df$X3 <- lead(df$X1, 1)
df$X3[seq(2, nrow(df), by = 2)] <- NA_character_