I am looking to add a column in my dataframe using the transform function. One of my column contains character strings as elements. I wish to find certain strings and add another column.
UNIT.NO. USAGE..kWh.month.
A1 863
A1 1339
D3 1058
D1 782
L1 1339
L7 1058
L1 782
I wish to add another column to classify category of data and get the following result:
UNIT.NO. USAGE..kWh.month. Category
A1 863 A
A1 1339 A
D3 1058 D
D1 782 D
L1 1339 L
L7 1058 L
L1 782 L
I used the following code but it doesn't work.
dataset.1<-transform(
dataset.1,
Category=
if(grepl("A",dataset.1$UNIT.NO.)==T){
"A"
} else
if(grepl("D",dataset.1$UNIT.NO.)==T){
"D"
} else
if(grepl("L",dataset.1$UNIT.NO.)==T){
"L"
}else{
"Other"
}
)
Warning in R : In if (grepl("A", dataset.1$UNIT.NO.) == T
) { :
the condition has length > 1 and only the first element will be used
Hence, all my Category values are now A and different characters are not being replaced as per their Unit No. What is the best way to add such a column.
I need these categories to perform a non parametric analysis. Thanks in advance.
dataset.1$Category <- substr(dataset.1$UNIT.NO,1,1)
?Other
argument?