2015-03-31 149 views
1

我有一个数据框。在它COL3的价值观和COL4是错行由1底行的值应该是前行中,最上面一行应在第二等从最后一行复制值并粘贴到第一行r

目前

col1 col2 col3 col4 
a b  c  d 
e  f  g  h 
i  j k  l 

应该

col1 col2 col3 col4 
    a b  k  l 
    e  f  c  d 
    i j  g  h 

我怎么在COL3和COL4仅移动值由一个打倒,最后成为第一个?

回答

1

假设d是你data.frame:

d$col3 <- c(d$col3[length(d$col3)], d$col3[-length(d$col3)]) 
d$col4 <- c(d$col4[length(d$col4)], d$col4[-length(d$col4)]) 
+0

此代码似乎没有在给定的采样数据题。 – 2015-03-31 07:41:24

+0

@TimBiegeleisen,代码中只有一个错字... – Cath 2015-03-31 07:56:17

+0

@Thomas,希望你不要介意输入错误 – Cath 2015-03-31 07:56:39

0

试试这个

df <- data.frame(col1=c("a", "e", "i"), 
       col2=c("b", "f", "j"), 
       col3=c("c", "g", "k"), 
       col4=c("d", "h", "l")) 


df <- cbind(df[, 1:2], df[c(dim(df)[1], 1:(dim(df)[1]-1)), 3:4]) 
0

使用的字符,而不是因素造成的数据帧:

df <- data.frame(col1=c("a", "e", "i"), 
       col2=c("b", "f", "j"), 
       col3=c("c", "g", "k"), 
       col4=c("d", "h", "l"), stringsAsFactors=FALSE) 

df$col3 <- c(df$col3[nrow(df)], df$col3[1:(nrow(df)-1)]) 
df$col4 <- c(df$col4[nrow(df)], df$col4[1:(nrow(df)-1)]) 

输出:

> df 
    col1 col2 col3 col4 
1 a b k l 
2 e f c d 
3 i j g h 
-1

假设DF是你的数据框,你可以使用一个for循环

temp3 = df[nrow(df),3] 
temp4 = df[nrow(df),4] 
for(i in 2:nrow(df)){ 
    df[(i,3] = df[((i - 1),3] 
    df[(i,4] = df[((i - 1),4] 
} 
df[1, 3] = temp3 
df[1, 4] = temp4 
2

我倾向于使用dplyr的mutate_eachsummarise_each功能相同的功能(S)适用于多列。这里是你如何能有一个自定义的“交换”功能接近它更好的可读性:

library(dplyr) 

定义一个函数:

swap <- function(x) c(last(x), head(x, -1L)) 

现在你可以使用这个自定义函数里面的“mutate_each”,并指定列要功能适用于:

mutate_each(df, funs(swap), col3, col4) 
# col1 col2 col3 col4 
#1 a b k l 
#2 e f c d 
#3 i j g h 

如果你喜欢基础R,你可以做到这一点SIM卡ilarly,使用稍微改性的功能“swap2”和“lapply”到函数应用到多个列:

# define the function: 
swap2 <- function(x) c(tail(x, 1L), head(x, -1L)) 
# define the columns you want to apply the function to: 
cols <- c("col3", "col4") 
# Finally, lapply over the data: 
df[cols] <- lapply(df[cols], swap2) 

数据:

> dput(df) 
structure(list(col1 = c("a", "e", "i"), col2 = c("b", "f", "j" 
), col3 = c("c", "g", "k"), col4 = c("d", "h", "l")), .Names = c("col1", 
"col2", "col3", "col4"), class = "data.frame", row.names = c(NA, 
-3L)) 
相关问题