for loop help calculating column based on another

rstudio

#1

Hello,

i have a data frame with 2 columns and i want o add a third based on what is contained in my second column,
i have columns speed ( integer) , column measure ( in knots and km) I want to add a column that calculates the km per hr speed if colunm 2 is knots or returns the value in the speed colum which is already in km , i have tried the below for loop which returns with an error "number of items to replace is not a multiple of replacement lengthnumber"

my for loop is

selected_storms_2$KM_Wind_Speed <- c()

for (j in 1: length(selected_storms_2$measure))
{
if(selected_storms_2$measure[j] == 'knots' )
{selected_storms_2$KM_Wind_Speed[j] <- selected_storms_2$Speed *1.8 }

else if (selected_storms_2$measure[j] == 'km' )
{selected_storms_2$KM_Wind_Speed[j] <- selected_storms_2$Speed}

}

can anyone see what i am doing wrong ? is there another way ?

many thanks


#2

You can use ifelse(), which is a vectorized function (i.e., no for loop required).

selected_storms_2$KM_Wind_Speed = ifelse(selected_storms_2$measure[j] == 'knots',
                                         selected_storms_2$Speed *1.8, 
                                         selected_storms_2$Speed)

If your measure column includes more values than 'knots' and 'km', then this will not work as written, but can be solved by nesting ifelse() statements.


#3

Hi

That has worked perfectly , think i was over complicating the process. Thanks for your help !


#4

In addition to the solution from hinkelman you can also do this by subsetting:

selected_storms_2$KM_Wind_Speed = selected_storms_2$Speed
selected_storms_2$KM_Wind_Speed[selected_storms_2$measure == 'knots'] = selected_storms_2$KM_Wind_Speed[selected_storms_2$measure == 'knots'] * 1.8

(This is one of the instances where I would love if R had the C-type operator +=, -=, *= and /= :grinning:)
Cheers
Steen


#5

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.