combining values of two variables together to create a new variable using r

67,968

Solution 1

If your dataframe is called x just paste them together (coerces to character) and then convert to numeric

x$pf <- as.numeric(paste(x$pgrp, x$fos, sep = ""))

(Do not use "data" as a name, that is a function already.)

Solution 2

You could use arithmetic (if fos is always < 10):

df <- within(df, pf <- pgrp * 10 + fos)
Share:
67,968
baz
Author by

baz

Updated on May 24, 2020

Comments

  • baz
    baz almost 4 years

    I need to create a new variable by combining the values of two existing variables

    anim <- c(1,2,3,4,5,6,7,8,9,10)
    pgrp <- c(1,3,2,4,2,3,1,2,4,3)
    fos <- c(2,1,1,2,1,2,1,2,2,1)
    data <- data.frame(anim,pgrp,fos)
    data
       anim pgrp fos
    1     1    1   2
    2     2    3   1
    3     3    2   1
    4     4    4   2
    5     5    2   1
    6     6    3   2
    7     7    1   1
    8     8    2   2
    9     9    4   2
    10   10    3   1
    

    I need my new variable "pf" to take the values of "pgrp" and "fos" as shown below

    data
       anim pgrp fos pf
    1     1    1   2 12
    2     2    3   1 31
    3     3    2   1 21
    4     4    4   2 42
    5     5    2   1 21
    6     6    3   2 32
    7     7    1   1 11
    8     8    2   2 22
    9     9    4   2 42
    10   10    3   1 31
    
  • Joshua Ulrich
    Joshua Ulrich almost 13 years
    tsk, tsk... df is also a function. ;-)
  • baz
    baz almost 13 years
    @mdsummer;@ Joshua Ulrich, thanks...would never use "data" it again as a dataframe name
  • Pulse
    Pulse about 10 years
    @mdsummer I tried it too, having two numeric variables but I only got a new one which has NAs, any ideas why this has happened? The one variable has missing values (NA) where the other one has numeric values and vice versa.
  • mdsumner
    mdsumner about 10 years
    No sorry. You'll need to reproduce, which btw is the easiest way to figure it out for yourself. Compare something like paste(c(1, NA, 2), 6:7)
  • Pulse
    Pulse about 10 years
    thank you for respoding, I do not understand what you mean by reproduce, I will ask a new question with this topic