Transform a specific row of a dataframe into a vector.

How to transform a specific row of a dataframe into a vector.

In this case, I would like to transform df1[3,2:3] into a vector.

Thank you so much!


df1<- structure(
  list(
   Name = c("Name1","Name2", "Name3","Name4","Name5","Name6"),
    Latitude = c(-24.930473, -24.930473,-24.95575,-24.95575,-24.950473,-24.950473), 
    Longitude = c(-49.994889,-49.994889, -49.990162,-49.990162,-49.996889,-49.996889)),
  row.names = c(NA, 6L), class = "data.frame")

df1[3,2:3]

> df1[3,2:3]
   Latitude Longitude
3 -24.95575 -49.99016

You can use unlist() to change to a named numeric vector.

df1<- structure(
  list(
    Name = c("Name1","Name2", "Name3","Name4","Name5","Name6"),
    Latitude = c(-24.930473, -24.930473,-24.95575,-24.95575,-24.950473,-24.950473), 
    Longitude = c(-49.994889,-49.994889, -49.990162,-49.990162,-49.996889,-49.996889)),
  row.names = c(NA, 6L), class = "data.frame")

df = df1[3,2:3]

str(df)
#> 'data.frame':    1 obs. of  2 variables:
#>  $ Latitude : num -25
#>  $ Longitude: num -50

# create a vector
my_vector = unlist(df1[3,2:3])

str(my_vector)
#>  Named num [1:2] -25 -50
#>  - attr(*, "names")= chr [1:2] "Latitude" "Longitude"

Created on 2023-01-31 with reprex v2.0.2.9000

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.