I need to convert a multi-row two-column data.frame
to a named character vector. My data.frame
would be something like:
dd = data.frame(crit = c("a","b","c","d"), name = c("Alpha", "Beta", "Caesar", "Doris") )
and what I actually need would be:
whatiwant = c("a" = "Alpha", "b" = "Beta", "c" = "Caesar", "d" = "Doris")
To create a vector of data frame values by rows we can use c function after transposing the data frame with t. For example, if we have a data frame df that contains many columns then the df values can be transformed into a vector by using c(t(df)), this will print the values of the data frame row by row.
enframe() converts a named vector to a tib- ble with a column of names and column of values.
enframe() converts named atomic vectors or lists to one- or two-column data frames. For a list, the result will be a nested tibble with a column of type list . For unnamed vectors, the natural sequence is used as name column.
Step 1: Here we create a DataFrame with name data. There is a total of two columns in DataFrame, short and name. To create a data frame, we use data.frame () function and then finally checkout our DataFrame by printing it. Step 2: Convert dataframe columns to a vector called result by use of setNames () function.
Sometimes all the columns in a data frame have similar data characteristics representing a particular variable. For example, having a data frame containing five columns each with heights of people. To convert this type of data frame into a vector we can use as.vector function along with the as.matrix function.
If two columns are of a form such that one column contains the name of the vector values and another column having the values of a vector then we might want to convert them into a vector. To do this, we can simply read the vectors with their data type and structure them with structure function.
We can use the as.matrix () function to quickly convert this data frame to a numeric matrix: #convert data frame to matrix mat <- as.matrix(df) #view matrix mat points assists rebounds [1,] 99 33 30 [2,] 90 28 28 [3,] 86 31 24 [4,] 88 39 24 [5,] 95 34 28 #view class of mat class (mat) [1] "matrix" "array"
Use the names
function:
whatyouwant <- as.character(dd$name) names(whatyouwant) <- dd$crit
as.character
is necessary, because data.frame
and read.table
turn characters into factors with default settings.
If you want a one-liner:
whatyouwant <- setNames(as.character(dd$name), dd$crit)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With