Question

Before, I asked this question: Moving certain elements of data frame into new columns (in R)

Now, I have the same data frame:

   > jiz <- data.frame(Type=c("X","B","B","B","B","X","B"),
+                   Action=c("both","1","2","2","1","both","1"))
> jiz
  Type Action
1    X   both
2    B      1
3    B      2
4    B      2
5    B      1
6    X   both
7    B      1

I would like to construct one new column, called "Result" with three values, "X", "Y" and "Z", depending on values from both columns "Type" and "Action".

If Type is 'X' and Action is 'both' --> "Result" is X

If Type is 'B' and Action is '1' --> "Result" is Y

If Type is 'B' and Action is '2' --> "Result" is Z,

such that new data frame becomes:

> jiz.new
  Type Action Result
1    X   both      X
2    B      1      Y
3    B      2      Z
4    B      2      Z
5    B      1      Y
6    X   both      X
7    B      1      Y

The transform + ifelse, from the post I linked to above, does not work for me here, because I have more than two combinations going into/creating the same new column.

Était-ce utile?

La solution

First, define a function:

conditionalResult <- function(argtype, argaction){
if (argtype=="X" & argaction=="both")
  return("X")
if (argtype=="B" & argaction==1)
  return("Y")
if (argtype=="B" & argaction==2)
  return("Z")

After function definition convert your data to data.table:

install.packages("data.table")
require("data.table")
jiz <- as.data.table(jiz)

And create a new conditional column:

jiz[, c("Result"):=conditionalResult(Type, Action)]

Voila, now you have new column called Result in your data.table with corresponding values.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top