将第二行作为R数据帧中的特定列值进行操作

时间:2018-09-25 18:53:38

标签: r

我有一个数据帧,其中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")

1 个答案:

答案 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_