R changing data type in a dataframe [duplicate]

Solution 1:

Short answer:

Vectors are sometimes also referred to as the ‘nuts & bolts’ in R as they build the basis for all complex objects such as data frames or fitted regression models:

  • You "pass" an atomic vector c(2022, "Y") to row 1 of df. In R atomic vectors contain only elements of same type e.g. all numeric, or all character...etc...
  • Atomic vectors are different to lists, lists can contain different types.
  • Atomic vectors are constructed with the c() function or the vector function.

In your case: character is over integer in the hierarchy of atomic vectors: therefore 2022 is transformed to character type.

Solution:

df$year <- as.integer(df$year)
str(df)
'data.frame':   1 obs. of  2 variables:
 $ year  : int 2022
 $ yes_no: chr "Y"