-5

I have a data table as follows:

x     y     z
1 head  car   toe
2 hand  nose  mouse
3 key   house ball

now I want to shift head, hand and ball to a new column and delete the word in the existing columns:

  x    y     z       new
1     car    toe     head
2     nose   mouse   hand
3 key house          ball

Could you help me out please? Thank you very much.

Reproducible Data:
df <- data.frame(
  V1   = 1:3, 
  x = c("head", "car", "toe"), 
  y = c("hand", "nose", "mouse"), 
  z = c("key", "house", "ball")
)
Amphetamim
  • 23
  • 5
  • 4
    Paste your example data as text, not image. Better yet, make it reproducible:https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – zx8754 Sep 25 '19 at 14:27
  • Just FYI: a data frame in R is conceptually not a spreadsheet where you can freely *shift* values from one cell to the other, but a set of (in many ways independent) vectors (*variables*) of equal length. – Roman Sep 25 '19 at 14:41

2 Answers2

0

Use dplyr for that such like this (let X be a data frame) for renaming or reordering/selecting columns.

library(dplyr)
X %>% rename(new=head)

or (to create a new order or a selection of columns)

X %>% select(x,y,z,`1`,car,toe)
0

Data

library (dplyr)
df <- data.frame(
        x = c("head", "hand", "key"),
        y = c("car", "nose", "house"),
        z = c("toe", "mouse", "ball"),
        stringsAsFactors = FALSE
    )

Code

# Add new column.
df_result <- df %>%
    mutate(
        new = case_when(
            x %in% c("head", "hand") ~ x,
            z == "ball" ~ z,
            TRUE ~ NA_character_
        )
    )
# Remove old values.
df_result$x[df_result$x %in% c("head", "hand")] <- NA_character_
df_result$z[df_result$z == "ball"] <- NA_character_

Result

> df_result
     x     y     z  new
1 <NA>   car   toe head
2 <NA>  nose mouse hand
3  key house  <NA> ball

Caveat: This approach prioritizes a "hand" or "head" in x before a "ball" in z.

Roman
  • 4,744
  • 2
  • 16
  • 58