tafelplankje
tafelplankje

Reputation: 583

Transfer variable type to another variable in R

I'd like to transfer the variable type from one variable to the other, where the variables are vectors.

for example x is numeric, y is character but I want it to be the same as x, how to do this? Same if x is integer etc.

pseudo code:

y <- set_variable_type(y,get_variable_type(x))

Upvotes: 0

Views: 200

Answers (1)

Andrew Ingalls
Andrew Ingalls

Reputation: 117

This has the potential for some errors to crop up. Like @r2evans mentioned converting some characters to numerics doesn't mesh well. It really depends on what the scope is for this code. If you know that type x will always be within certain confines, you will probably be fine with their suggestion class(y)<-class(x), but if you don't know what x will always be, you could end up trying to convert a dataframe into a int, which will throw an error. I would suggest approaching your problem a different way. With more information we may be able to help you find a more comprehensive solution to the problem. (I still can't comment yet, or this would be a comment).

Upvotes: 1

Related Questions