Skip to contents

dta_transpose() transposes a data frame, optionally using a specified column as the names for the resulting variables. The function can also convert numeric strings to numeric values in the transposed data frame.

Usage

dta_transpose(dat, .column_to_use_as_variables = NULL)

Arguments

dat

A data frame or tibble to transpose.

.column_to_use_as_variables

A column name to use as variable names in the transposed data frame. If left empty, default column names "V1", "V2", ... will begenerated.

Value

A transposed data frame with specified or generated column names.

Details

The function first checks if the input is a valid data frame or tibble. If a column is specified via .column_to_use_as_variables, its values are used as the column names for the transposed data frame, and the column is removed from the input before transposing. If no column is specified, default column names are generated in the format "V1", "V2", ....

After transposition, the dta_to_numeric() function is applied to ensure any numeric strings in the transposed data frame are converted to numeric values.

Examples

data("data_cancer")
dta_gtable(data_cancer)
cancer_type V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17
stomach 124 42 25 45 412 51 1112 46 103 876 146 340 396



bronchus 81 461 20 450 246 166 63 64 155 859 151 166 37 223 138 72 245
colon 248 372 189 1843 180 537 519 455 406 365 942 776 372 163 101 20 283
ovary 1234 89 201 356 2970 456










# Transpose the data frame and use column 1 as variable # names in the transposed data frame. df <- dta_transpose( dat = data_cancer, .column_to_use_as_variables = 1 ) dta_gtable(df)
stomach bronchus colon ovary
124 81 248 1234
42 461 372 89
25 20 189 201
45 450 1843 356
412 246 180 2970
51 166 537 456
1112 63 519
46 64 455
103 155 406
876 859 365
146 151 942
340 166 776
396 37 372

223 163

138 101

72 20

245 283
# You could also specify the variable name df2 <- dta_transpose( dat = data_cancer, .column_to_use_as_variables = cancer_type ) dta_gtable(df2)
stomach bronchus colon ovary
124 81 248 1234
42 461 372 89
25 20 189 201
45 450 1843 356
412 246 180 2970
51 166 537 456
1112 63 519
46 64 455
103 155 406
876 859 365
146 151 942
340 166 776
396 37 372

223 163

138 101

72 20

245 283
# Use default column names data("data_cancer2") # does not have cancer types column dta_gtable(data_cancer2)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17
124 42 25 45 412 51 1112 46 103 876 146 340 396



81 461 20 450 246 166 63 64 155 859 151 166 37 223 138 72 245
248 372 189 1843 180 537 519 455 406 365 942 776 372 163 101 20 283
1234 89 201 356 2970 456










# Transpose and use default column names "V1", "V2", ... df3 <- dta_transpose(data_cancer2) dta_gtable(df3)
V1 V2 V3 V4
124 81 248 1234
42 461 372 89
25 20 189 201
45 450 1843 356
412 246 180 2970
51 166 537 456
1112 63 519
46 64 455
103 155 406
876 859 365
146 151 942
340 166 776
396 37 372

223 163

138 101

72 20

245 283