Home > Net >  Change type from AsIs to list in R dataframe
Change type from AsIs to list in R dataframe

Time:11-16

I'm trying to make a dataframe in R that looks like this:

    group   numbers
1    1     [1,2,3,4,5]
2    2     [8,9,10,11]

The way I went about it was as follows:

group = c(1:2)
numbers = I(list((1:5),(8:11)))
df = data.frame(group,numbers)
class(df$numbers)

However, when I get the class of df$numbers I get "AsIs". This is causing problems later on down the line because I am using this in SparkR and Spark cannot handle types of "AsIs". For my usecase, I need the class to be "list" but when I do as.list() it still doesn't change the type. And it will be helpful to keep the class of group as "integer" but I think casting it to integer still works, if it wasn't already an integer.

Is there another way to avoid this issue with AsIs and make the dataframe as shown?

CodePudding user response:

You could unclass the numbers:

df$numbers <- unclass(df$numbers)

df
  rank       numbers
1    1 1, 2, 3, 4, 5
2    2  8, 9, 10, 11

str(df)
'data.frame':   2 obs. of  2 variables:
 $ rank   : int  1 2
 $ numbers:List of 2
  ..$ : int  1 2 3 4 5
  ..$ : int  8 9 10 11

Or do not use the inhibitor function I:

df <- data.frame(group = 1:2)
df$numbers <- list((1:5),(8:11))

 df
  group       numbers
1     1 1, 2, 3, 4, 5
2     2  8, 9, 10, 11
  • Related