Home > Software design >  How do you add a new column in R and assign specific values to specific rows?
How do you add a new column in R and assign specific values to specific rows?

Time:12-11

I have an existing dataframe e.g.:

Sample Source 1 2
5-SC Uintas x y
5-SC SM x y
5-SC CMB x y
5-SC Uintas x y
5-SC SM x y
5-SC CMB x y

I'd like to add a column after "Sample" wherein i assign specific values to specific rows e.g.:

Sample Metric Source 1 2
5-SC CC Uintas x y
5-SC CC SM x y
5-SC KV Uintas x y
5-SC KV SM x y
5-SC KSD Uintas x y
5-SC KSD SM x y

This is my failing effort so far:

data <- add_column(data, Metric = (CC %in% c(1:2), KV %in% c(3:4), KSD %in% c(5:6)),.after = 'Sample_ID')

Please forgive the simplicity of this question, but i simply can't figure it out no matter how i Google things or sift through SO.

Thanks in advance for the help!

CodePudding user response:

library(tidyverse)
df %>%
  add_column(Metric = rep(c('CC', 'KV', 'KSD'), each = 2), .after = 'Sample')

 Sample Metric Source X1 X2
1   5-SC     CC Uintas  x  y
2   5-SC     CC     SM  x  y
3   5-SC     KV    CMB  x  y
4   5-SC     KV Uintas  x  y
5   5-SC    KSD     SM  x  y
6   5-SC    KSD    CMB  x  y

CodePudding user response:

Base R option

df$Metric = rep(c('CC', 'KV', 'KSD'), each = 2)
df <- df[, c(1, 5, 2:4)]

Output

  Sample Metric Source X1 X2
1   5-SC     CC Uintas  x  y
2   5-SC     CC     SM  x  y
3   5-SC     KV    CMB  x  y
4   5-SC     KV Uintas  x  y
5   5-SC    KSD     SM  x  y
6   5-SC    KSD    CMB  x  y

Data

df <- structure(
  list(
    Sample = c("5-SC", "5-SC", "5-SC", "5-SC", "5-SC",
               "5-SC"),
    Source = c("Uintas", "SM", "CMB", "Uintas", "SM", "CMB"),
    X1 = c("x", "x", "x", "x", "x", "x"),
    X2 = c("y", "y", "y", "y", "y", "y")
  ),
  class = "data.frame",
  row.names = c(NA,-6L)
)
  • Related