Reputation: 35
I have a column that contains some values as follows: 0 to 6 Each value refers to account type, whether revenue, expense etc
I am trying to use IF to look for the value and assign it its correct classification.
I have tried the following but it didn't work.
account_type <- if(df$class = 0) {
account_type = 'Suspense'
} else if (df$class = 1) {
account_type = 'Asset'
}
I do appreciate your help. I would also appreciate it if you combine an explanation.
Thanks,
Upvotes: 0
Views: 65
Reputation: 4505
I guess that more preferable, R-ish way to do what you are trying to do, is to use a lookup table.
First, I create a reproducible example:
set.seed(68826333)
(
dat <- data.frame(
account = sample(1:4, 10, TRUE),
value = rnorm(10)
)
)
# account value
#1 2 1.17913936
#2 1 -1.40654534
#3 3 -2.46079924
#4 1 -0.20670095
#5 1 -1.29534910
#6 1 0.80030380
#7 4 0.37431903
#8 4 -0.07338782
#9 1 -0.50872642
#10 4 -0.15198686
Then I create a lookup table:
(
lookup <- c('1' = 'Asset', '2' = 'Suspense', '3' = 'Revenue', '4' = 'Expense')
)
# 1 2 3 4
# "Asset" "Suspense" "Revenue" "Expense"
In my lookup table names of the vector corresponds to values of the account
variable from dat
.
Now, whenever you want to map your numerical data from account
variable into account types, you can do just simple subsetting and reassignment:
dat$account <- lookup[as.character(dat$account)]
#dat
# account value
#1 Suspense 1.17913936
#2 Asset -1.40654534
#3 Revenue -2.46079924
#4 Asset -0.20670095
#5 Asset -1.29534910
#6 Asset 0.80030380
#7 Expense 0.37431903
#8 Expense -0.07338782
#9 Asset -0.50872642
#10 Expense -0.15198686
Upvotes: 1
Reputation: 389275
If you already have a dataframe with class value and name then using merge
is the easiest way.
Here is another way using recode
where you can specify from and to values.
library(dplyr)
df <- df %>% mutate(account_type = recode(class, `1`='Suspense', `2` = 'Asset'))
df
Upvotes: 0
Reputation: 35
I have used merge and it worked:
I created a new dataset and included the account types and called it class merged1 is the first dataset that includes the full account numbers
merged2 <- merge(merged1, class, by.x = "classification", by.y = "class")
I am still willing to see more answers if there is an easier way, I am new to R and programming languages.
Thanks,
Upvotes: 0