R语言中如何在字符表与数值表之间建立关联?
Hey there! Let's figure out how to link your c2 matrix and data1 data frame in R. First, let's recap what each of these objects contains (here's your original code for reference):
# Define product names and matrix c2 c1 <- c("product a1","product a2","product a3","product b1","product b2","product b3") c2 <- matrix(c1, nrow=2, ncol=3, dimnames = list(c("productline a","productline b"),c("1","2","3"))) # Define numerical data frame data1 company1 <- c(0,1,0,0,0,0) company2 <- c(0,0,0,1,1,0) company3 <- c(1,1,0,0,0,0) data1 <- data.frame(company1,company2,company3,row.names = c1)
The key connection here is that every product name in c2 is exactly a row name in data1—that's our link! Here are a few practical ways to formalize this association:
Method 1: Combine into a single unified data frame
If you want all metadata (product line, product number) and numerical data in one place, convert c2 to a long-format data frame and merge it with data1:
# Convert c2 to a long data frame with product line, number, and name c2_long <- as.data.frame.table(c2, stringsAsFactors = FALSE) colnames(c2_long) <- c("product_line", "product_number", "product_name") # Merge with data1 using product names to match rows merged_data <- merge(c2_long, data1, by.x = "product_name", by.y = "row.names")
The result merged_data will have columns for product_line, product_number, product_name, plus all the company values from data1—everything linked neatly together.
Method 2: Extract numerical data by product line
If you just need to pull numerical records for a specific product line from data1, use the product names in c2 to filter rows:
# Get all data for productline a productline_a_data <- data1[rownames(data1) %in% c2["productline a", ], ] # Get all data for productline b productline_b_data <- data1[rownames(data1) %in% c2["productline b", ], ]
This is great for quick group-specific analysis—you can immediately work with only the rows tied to a particular product line.
Method 3: Add product line/number columns directly to data1
If you want to augment your original data1 with the metadata from c2, create mapping tables and use match() to attach the info:
# Create a product name -> product line mapping product_to_line <- stack(as.data.frame(c2)) colnames(product_to_line) <- c("product_name", "product_line") # Add product line column to data1 data1$product_line <- product_to_line$product_line[match(rownames(data1), product_to_line$product_name)] # Create a product name -> product number mapping product_to_number <- data.frame( product_name = as.vector(c2), product_number = rep(colnames(c2), each = nrow(c2)) ) # Add product number column to data1 data1$product_number <- product_to_number$product_number[match(rownames(data1), product_to_number$product_name)]
Now data1 includes columns for product_line and product_number right alongside the company values, making it easier to do grouped operations or visualizations later.
内容的提问来源于stack exchange,提问作者Codezy

